content stringlengths 5 1.05M |
|---|
import os
import time
import hashlib
import base64
import base58
import datetime
import coincurve
import subprocess
import binascii
import json
import copy
import web3
import asyncio
import websockets
import threading
from .base import Logger, LogicException, TimeOutException, InvalidArgumentsException, BadResultExcep... |
# -*- coding: utf-8 -*-
"""Tests for course_extensions mixins."""
from __future__ import absolute_import, unicode_literals
import mock
from xmodule import course_module
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from .. import... |
import json
from os import getcwd
from pathlib import Path
import sys
import jinja2
from .model import PropertyModel
from .node_type import collect_node_types
def main():
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("module")
parser.add_argument("-o", dest="outp... |
from collections import OrderedDict
import io
from functools import partial
import json
import logging
import math
from multiprocessing.dummy import Pool
import os
import re
import shutil
from tempfile import TemporaryDirectory
import requests
from requests import HTTPError
from civis import APIClient, find_one
from ... |
#
# @lc app=leetcode id=9 lang=python3
#
# [9] Palindrome Number
#
# @lc code=start
class Solution:
def isPalindrome(self, x: int) -> bool:
digits = str(x)
lower = 0
upper = len(digits) - 1
while lower <= upper:
if digits[lower] != digits[upper]:
retur... |
class Mail:
def __init__(self, sender, to, subject, body):
self.sender = sender
self.to = to
self.subject = subject
self.body = body
self.mail = f"From: {self.sender}\nTo: {self.to}\nSubject: {self.subject}\n\n{self.body}"
def __str__(self):
return(self.mail)
if ... |
import boto3
from kleenlogger import kleenlogger
class S3Service:
def __init__(self):
self.service = None
self.bucket = None
def init_service(self, aws_key, aws_secret, bucket):
kleenlogger.logger.info('Initializing S3 service')
self.service = boto3.client('s3', aws_access_ke... |
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:title>", views.entry, name="entry"),
path("search/", views.search, name="search"),
path("create", views.create, name="create"),
path("edit", views.edit, name="edit"),
path("sav... |
from django.views.decorators.http import require_http_methods
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView, UpdateView
from django.views.generic.list import ListView
from django.db.models import Count, Q
from django.contrib.auth.decorators import permission_require... |
from dateutil import rrule
import datetime
def workdays(start, end, holidays=0, days_off=None):
if days_off is None:
days_off = 5, 6 # default to: saturdays and sundays
workdays = [x for x in range(7) if x not in days_off]
days = rrule.rrule(rrule.DAILY, dtstart=start, until=end,
... |
#!/usr/bin/env python
import sys
import os
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
here = os.path.abspath(os.path.dirname(__file__))
about = {}
with open(os.path.join(here, 'graphdiff', '__version__.py'), 'r') as f:
exec(f.read(), about)
with open('REA... |
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth import login
from .forms import SignupForm
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# Dependencies
from bs4 import BeautifulSoup as bs
import requests
import os
from splinter import Browser
import pandas as pd
from webdriver_manager.chrome import ChromeDriverManager
from pprint import pprint
import pymongo
from flask import Flask, render_template
impor... |
import asyncio
from unittest import mock
import pytest
from sqlalchemy import Column, Integer, MetaData, String, Table, func, select
from aiopg import sa
meta = MetaData()
tbl = Table(
"sa_tbl2",
meta,
Column("id", Integer, nullable=False, primary_key=True),
Column("name", String(255)),
)
@pytest.f... |
import cli
from setuptools import setup
NAME = "gui"
def read(filename):
try:
with open(filename) as fp:
content = fp.read().split("\n")
except FileNotFoundError:
content = []
return content
setup(
author="Quinten Roets",
author_email="quinten.roets@gmail.com",
d... |
from pluggie import Pluggie
plug = Pluggie()
@plug.preprocess_event
def my_function(a, b=1):
print("a={}, b={}".format(a, b))
return a * b
assert my_function(2) == 2
plug.load_plugin('demo_plugin.py')
assert my_function(2) == 12
assert my_function(2, b=1) == -4
|
"""Functional tests for Yandex.Weather custom integration."""
|
"""
Kademlia is a Python implementation of the Kademlia protocol which
utilizes the asyncio library.
"""
__version__ = "2.0"
|
'''
HAL Tokenzier
This module reads and tokenizes HAL2 (HotKey's Average Language 2) source,
and "streams" it to a parser/translator.
Used to convert HAL into another language using a HTK ("HAL Translation Kernel" or "HAL Token Konverter" :) )
'''
from src.htk.py.lib import *
TOKEN_IDLE = 0
TOKEN_COMMENT = ... |
from logging import getLogger
from subprocess import check_call
import sys
import importlib
log = getLogger(__name__)
PY_EXEC = sys.executable if not " " in sys.executable else '"' + sys.executable + '"'
def require(dep):
while True:
try:
m = importlib.import_module(dep)
return m
... |
from typing import Union
class Filter:
def __init__(self, _filter_yaml, app=None) -> None:
self.app = app # type: str
self.component = _filter_yaml.get('component') # type: str
self.archive = _filter_yaml.get('archive') # type: str
self.origin = _filter_yaml.get('origin') # ty... |
from neet.network import Network
from neet.boolean import LogicNetwork
from time import time
import matplotlib.pyplot as plt
import neet.boolean.examples as ex
import numpy as np
import os
def make_network(net, trans):
"""
Given a network and desired state transitions, construct a `LogicNetwork`
which imp... |
"""
"""
# Created on 2013.07.15
#
# Author: Giovanni Cannata
#
# Copyright 2013 - 2018 Giovanni Cannata
#
# This file is part of ldap3.
#
# ldap3 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either ... |
'''TAQ data plot module.
The functions in the module plot the data obtained in the
taq_data_analysis_avg_responses_physical module.
This script requires the following modules:
* matplotlib
* numpy
* pickle
* taq_data_tools_avg_responses_physical
The module contains the following functions:
* taq_... |
# twitter config
consumer_key = 'CONSUMER_KEY'
consumer_secret = 'CONSUMER_SECRET'
access_token = 'ACCESS_TOKEN'
access_token_secret = 'ACCESS_TOKEN_SECRET'
# koto config
rpc_user = 'RPC_USER'
rpc_password = 'RPC_PASSWORD'
rpc_port = '8432'
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 10 12:03:42 2018
@author: 北海若
"""
import game_utils as gu
import time
import os
import subprocess
import psutil
# Config for Auto Replay to Data
AUTO = True
BEGIN = 0
END = 5518
REPLAY_PATH = r"D:\AI_DataSet\DATASET_REMI"
EXE_PATH = r"D:\AI_DataSet\TH123\th123\th123.ex... |
from setuptools import setup, find_packages
setup(name='create2api',
version='0.1',
description='Library for controlling the iRobot Create2',
url='https://github.com/pomeroyb/Create2Control',
author='Brandon Pomeroy',
author_email='brandon@pomeroyb.com',
license='MIT',
zip_saf... |
from datetime import datetime
import punters_client
import pytest
@pytest.fixture(scope='module')
def expected_values(runner, source_timezone):
return {
'url': runner['horse_url'],
'name': 'Tycoon Tony',
'colour': 'bay',
'sex': 'gel... |
import json
import urllib3
from botocore.config import Config
import botocore
import boto3
import enum
import traceback
import time
CREATE_SUCCEEDED = "CREATE_COMPLETE"
CREATE_FAILED = ["CREATE_FAILED", "ROLLBACK_COMPLETE", "ROLLBACK_FAILED"]
DELETE_SUCCEEDED = "DELETE_COMPLETE"
DELETE_FAILED = ["DELETE_FAILED", "ROL... |
from pprint import pformat
from django.core.management.base import BaseCommand
from django.conf import settings
from ..bower import bower_adapter
from ..exceptions import BowerNotInstalled
class BaseBowerCommand(BaseCommand):
"""Base management command with bower support"""
def handle(self, *args, **options)... |
# Insort keeps a sorted sequence always sorted
import bisect
import random
SIZE = 7
random.seed(1729) # Initialize the random number generator.
my_list = []
for i in range(SIZE):
# This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.
new_item = random.randrange(... |
# Imports
from .preprocess import preprocess
from .logger import logger
import simpy
###
global queues
global QUEUES_AUX
global LOST
global SERVED
LOST = 0
SERVED = 0
SIM_TIME = 200
env = simpy.Environment()
path = 'data/data.json'
data = preprocess(path)
MY_RANDOM_NUMBERS = data[3]
class Queue(object):
def _... |
# Copyright 2014-2015 ARM Limited
#
# 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 w... |
from baseline.densenet import Densex2
from baseline.resnet import Resx2, SimRes
from common.trainer import getTestComponents
from spectrainer import ToyNetTrainer
from toynet.toynetv1 import ToyNetV1
def main():
# for capability when spawn start
trainer, net, data = getTestComponents(
ToyNetTrainer, D... |
from __future__ import print_function
import sys
from Ziggeo import Ziggeo
import json
if(len(sys.argv) < 5):
print ("Error\n")
print ("Usage: $>python video_push.py YOUR_API_TOKEN YOUR_PRIVATE_KEY VIDEO_TOKEN PUSH_SERVICE_TOKEN\n")
sys.exit()
api_token = sys.argv[1]
private_key = sys.argv[2]
video_token = sys.arg... |
from typing import Optional, Type
from tortoise import fields, models
from tortoise.exceptions import DoesNotExist
from fastapi_users.db.base import BaseUserDatabase
from fastapi_users.models import UD
class TortoiseBaseUserModel(models.Model):
id = fields.CharField(pk=True, generated=False, max_length=255)
... |
import numpy as np
import argparse
import time
import cv2
import os
class ObjectDetector:
def __init__(self, confidence=0.4, nms_thresh=0.4):
self.confidence = confidence
self.nms_thresh = nms_thresh
# load the COCO class labels our YOLO model was trained on
labelsPath = "data/coco.names"
self.LABELS = o... |
from buff.trinket.zug import Zug
from rotation.executors import Executor
class ZugExecutor(Executor):
def __init__(self):
super().__init__(Zug())
def attempt_cast_impl(self, rotation, engine, char_state):
priority = engine.current_priority()
if self.spell.next_available > priority:
... |
import sys, os.path
from StringIO import StringIO
from twisted.trial import unittest
from twisted.internet import defer
from twisted.application import service
from foolscap.api import Tub, eventually
from foolscap.appserver import cli, server, client
from foolscap.test.common import ShouldFailMixin, crypto_available... |
import sqlite3
def databaseentry(ir,hr):
con = sqlite3.connect('static/data.db')
params = dict()
try:
with con:
cur = con.cursor()
cur.execute('INSERT OR IGNORE INTO data (ir,hr) VALUES (?, ?)', (ir,hr))
con.commit()
params['status... |
import json
import os
import time
from typing import List
import aiopg
import psycopg2
import psycopg2.extras
# baselevel classes from shared data adapter to inherit from.
from services.data.postgres_async_db import \
_AsyncPostgresDB as BaseAsyncPostgresDB
from services.utils import DBConfiguration, logging
from... |
from typing import List, Callable
import numpy as np
from GPy.core.parameterization.priors import Gaussian
from src.autoks.backend.kernel import decode_kernel, decode_prior, set_priors
from src.autoks.core.covariance import all_pairs_avg_dist, kernel_to_tree, kernel_l2_dist
from src.autoks.core.gp_model import GPMode... |
import argparse
import logging
import neptune
import pandas as pd
import os
import nohossat_cas_pratique
from nohossat_cas_pratique.preprocessing import split_data
from nohossat_cas_pratique.modeling import get_model, run_grid_search, create_pipeline
from nohossat_cas_pratique.monitor import save_artifact, record_met... |
"""
A modied version of the code by Tae Hwan Jung
https://github.com/graykode/modelsummary
"""
import torch
import numpy as np
import torch.nn as nn
from collections import OrderedDict
def summary(model, input_shape, batch_size=-1, intputshow=True):
def register_hook(module):
def hook(module, input, outp... |
ReLU
[[0.0757265, 0.390525, 0.536794, 0.372584, -0.0462552], [0.0347555, 0.167795, -0.0624365, 0.334343, -0.43094], [0.289983, -0.0414354, -0.0545657, 0.198848, -0.0189019], [0.0477393, -0.925532, -0.0879031, 0.0295315, -0.0929011], [-0.129882, 0.161167, 0.837348, 0.0436584, 0.0229265], [-0.00859446, -0.00679297, -0.01... |
import logging
from nfp.servicos.controles.notas_fiscais import (selecionar_execucao, finalizar_execucao,
contar_processos_executados, selecionar_tarefa_ativa)
from nfp.servicos.interface import abrir_popup
from nfp.telas.nfp import Nfp
from nfp import EXIBIR_POPUP_RESU... |
from ooMisc import assignScript
from baseProblem import MatrixProblem
from numpy import asfarray, ones, inf, dot, nan, zeros, any, isfinite, sign
from ooMisc import norm
import NSP
class LLAVP(MatrixProblem):
_optionalData = ['damp', 'X', 'c']
allowedGoals = ['minimum', 'min']
def __init__(self, *args, **k... |
from cog.core import Record
from cog.core import Table
from cog import config
import logging
import os
import shutil
from logging.config import dictConfig
import string
import random
import unittest
DIR_NAME = "TestIndexer"
class TestIndexer(unittest.TestCase):
@classmethod
def setUpClass(cls):
path... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-01-16 08:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('digi', '0011_fix_guidepages_fields'),
]
operations = [
migrations.AddField(... |
name = 'arraymin'
|
"""
algorithms
Created by: Martin Sicho
On: 25-02-20, 15:13
"""
from abc import ABC, abstractmethod
import openTSNE
from pandas import DataFrame, Series
from genui.maps.models import Point
from genui.models.genuimodels.bases import Algorithm
from genui.models.models import ModelParameter
class MapAlgorithm(Algorith... |
"""Calculations used by Sales Tax Calculator program."""
# The sales tax rate as a %, must divide by 100 for a decimal value.
SALES_TAX_RATE = 6
def get_sales_tax(subtotal):
"""Return the sales tax of a given value."""
return round(subtotal * SALES_TAX_RATE/100, 2)
def get_total(subtotal):
"""R... |
#
# Copyright (c) 2021 IBM Corp.
# 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... |
import pytest
import test_helpers
from django.urls import reverse
from django.test import Client
pytestmark = [pytest.mark.django_db]
def tests_Profile_list_view():
instance1 = test_helpers.create_staff_app_Profile()
instance2 = test_helpers.create_staff_app_Profile()
client = Client()
url = revers... |
#!usr/bin/env python
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Copyright 2013 California Institute of Technology. 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 m... |
"""Main module."""
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Time 4 Files
Copy all files from given directory,
trying extract creation time,
and append this time info to
"""
import sys
import os
import optparse
import time
import shutil
import datetime
import atomic_transformation as at
import pyfast... |
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.chrome.options import Opti... |
class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
if len(nums) == m:
return max(nums)
lo, hi = max(nums), sum(nums)
while (lo < hi):
mid = (lo + hi) // 2
temp, cnt = 0, 1
for num in nums:
temp += num
... |
from django.core.management.base import BaseCommand, CommandError
from tracking.harvest import save_tracplus
class Command(BaseCommand):
help = "Runs harvest_tracking_trackplus to harvest points"
def handle(self, *args, **options):
self.stdout.write("Harvesting TracPlus feed")
try:
... |
from django.contrib import admin
# Register your models here.
from .models import *
admin.site.register(Product)
admin.site.register(Product_categories)
admin.site.register(ProductImage) |
"""num.py
Tools for numerical operations.
"""
from typing import Sequence, Tuple, Union, List, Optional
import numpy as np
import pandas as pd
from ..utils.misc import unwrap_optional
INTTYPES = [int, np.int, np.int16, np.int32, np.int64]
FLOATTYPES = [float, np.float, np.float16, np.float32, np.float64,
... |
""" Skip the origin Gohlke transforms for doctests.
That file needs some specific doctest setup.
"""
from os.path import join as pjoin
collect_ignore = [pjoin('proj1', "conf.py"), 'rst_md_files']
|
#!/usr/bin/python3
from __future__ import absolute_import, print_function, unicode_literals
import sys
import os
import sqlite3
cdir = os.path.dirname( os.path.realpath(__file__) )
sys.path.insert(0, cdir+"/..")
import pypdx
def test_module():
dsn = ':memory:'
xmlfile = os.path.join(cdir,"../pypdx/data/... |
# -*- coding: utf-8 -*-
import numpy as np
from numba import jit
from .frutils import max_frontwidth_bulk, flatsize_sym, flatind_sym
from .topo import signed_topo_bulk
@jit(nopython=True, nogil=True, cache=True)
def frontal_sym_bulk_uniform(A: np.ndarray, topology: np.ndarray,
B: np.ndar... |
import tkinter as tk
import tkinter.ttk as ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import numpy as np
def on_canvas_click(event):
if event.inaxes:
event.inaxes.plot([event.xdata], [event.ydata], marker="o", color="r")
... |
import flask_graphql
from flask_graphql.graphqlview import HttpError
import json
from werkzeug.exceptions import BadRequest
class GraphQLView(flask_graphql.GraphQLView):
def parse_body(self, request):
content_type = self.get_content_type(request)
if content_type == 'application/graphql':
... |
from torchpack.datasets.dataset import Dataset
import torch
import numpy as np
class Classification2Dataset(torch.utils.data.Dataset):
def __init__(self, num=11):
self.data = []
self.target = []
sum0 = 0
sum1 = 0
for x in np.linspace(0, 1, num=num):
for y in np.l... |
import sqlite3
connection = sqlite3.connect("classRoomDB.db")
cursor = connection.cursor()
# createTable = """
# CREATE TABLE classroom (
# student_id INTEGER PRIMARY_KEY,
# name VARCHAR,
# gender CHAR(1),
# physicsMarks INTEGER,
# mathsMarks INTEGER,
# chemistryMarks INTEGER
# )
# """
#
# cursor.execute(createTable... |
from Components.Language import language
from Tools.Directories import resolveFilename, SCOPE_PLUGINS
from os import environ as os_environ
import gettext
def localeInit():
lang = language.getLanguage()[:2]
os_environ['LANGUAGE'] = lang
gettext.bindtextdomain('EPGCacheSelector', resolveFilename(SCOPE_PLUGIN... |
# Generated by Django 2.2.9 on 2020-02-07 10:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("socialprofile", "0002_models_proxy"),
("socialprofile", "0002_auto_20170107_0237"),
]
operations = []
|
from math import ceil, floor
from statistics import mean
if __name__ == '__main__':
with open('input', 'r') as file:
crabs = [int(i.strip()) for i in file.readline().split(',')]
m = mean(crabs)
m = floor(m)
n = ceil(m)
f = 0
for c in crabs:
d = abs(c - m)
e = abs(c - n)
... |
'''
'''
import logging
from .coco_converters.coco_to_sa_pixel import (
coco_instance_segmentation_to_sa_pixel,
coco_panoptic_segmentation_to_sa_pixel
)
from .coco_converters.coco_to_sa_vector import (
coco_instance_segmentation_to_sa_vector,
coco_keypoint_detection_to_sa_vector, coco_object_detection_t... |
#
# Copyright (c) 2020 Kian Cross
#
from typing import cast
from pixy.escape_sequence import EscapeSequence
from pixy.colours import constants
class TrueColour(EscapeSequence):
__MAX_VALUE = 0xFF
__RGB_SUB_CODE = 2
def __new__(
cls, red: int, green: int, blue: int, background: bool = False
... |
#Copyright (c) 2014 Sony Computer Entertainment America LLC. See License.txt.
import sys
sys.path.append("./CommonTestScripts")
import Test
import FsmUtil
atfDocService.OpenNewDocument(editor)
Test.Equal(0, fsm.Transitions.Count, "Verify new document has no transitions")
statesLeft = []
statesRight =... |
""" Support for controlling agents """
__author__ = 'Michael Meisinger'
from pyon.public import log, RT, BadRequest, Container, NotFound
from ion.core.process.proc_util import ProcessStateGate
from interface.services.agent.istreaming_agent import StreamingAgentProcessClient
class AgentControl(object):
def __i... |
#!/usr/bin/env python
#The MIT License (MIT)
#Copyright (c) 2016 Massimiliano Patacchiola
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
#MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ... |
#
# This file is part of pyasn1-alt-modules software.
#
# Created by Russ Housley
# Copyright (c) 2019-2021, Vigil Security, LLC
# License: http://vigilsec.com/pyasn1-alt-modules-license.txt
#
import sys
import unittest
from pyasn1.codec.der.decoder import decode as der_decoder
from pyasn1.codec.der.encoder import enc... |
"""
This file holds functions that reproduce the commands available in the editor (http://zetaflow.skylogic.ca/game/edit)
"""
# Note: argument 'parts' is EITHER a single part number (string or int) OR a list (array) of part numbers
def parts_to_string(parts):
if (isinstance(parts, list)):
return ','.join([str(x) f... |
class HTTPException(Exception):
def __new__(cls, message: str) -> object:
return super().__new__(cls, message)
class APIException(HTTPException):
pass
class APIWarning(Warning):
pass
def raise_error(response) -> None:
code = response['code']
error = response['error']
raise APIExcep... |
"""
This python script contains commonly used functions to help with parsing in the openelections project.
Original Author: Tiffany Xiao
Date Created: 11/9/2019
"""
import csv
import PyPDF2
def csv_to_dict(csv_file_name):
'''Function to convert a csv with two columns into a dictionary (the first column is the va... |
import streamlit as st
# To make things easier later, we're also importing numpy and pandas for
# working with sample data.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
st.header('eCommerce Customer Behavior')
st.subheader('This is a subhead... |
class Logger:
def __init__(self, prefix: str) -> None:
self.prefix = prefix
def __compose(self, level: str, msg: str) -> str:
return "{} {}: {}".format(self.prefix, level, msg)
def info(self, msg: str) -> None:
print(self.__compose("INFO", msg))
def warn(self, msg: s... |
"""""
Datos de Entrada
N Enteros Positivos = n = int
K Enteros Positivos = k = int
Datos de Salida
Siempre que k sea menor a n
Cuando N = K
"""""
n=int(input("Escriba el primer digito "))
k=int(input("Escriba el primer digito "))
while True:
n=0
if(k<n):
n=n-1
print(n)
elif(n==k):
... |
# Generated by Django 3.0.5 on 2020-04-16 07:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('academics', '0004_program_career_prospectus'),
]
operations = [
migrations.AlterField(
model_name='program',
name='c... |
# -*- coding: utf-8 -*-
"""
pip_services_runtime.cache.__init__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Cache module initialization
:copyright: Digital Living Software Corp. 2015-2016, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
__all__ = ['CacheEntry', 'Ab... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
import pytest
@pytest.fixture
def new_center_param():
return {
"center_code": "NEWYORK001",
"name": "NewYork 001",
"staff_members": {
"uuid": ['b77a1d4f921d460a9eb179d45ba56f51']
}
}
@pytest.fixture
def existing_center():
return {
"uuid": "48574f05-a29... |
from __future__ import print_function, division, absolute_import
from glue.external.echo import CallbackProperty
from glue.core.state_objects import State
class SAMPState(State):
status = CallbackProperty('Not connected to SAMP Hub')
connected = CallbackProperty(False)
clients = CallbackProperty([])
... |
from __future__ import absolute_import
import sys
from lib2to3.main import main
if __name__ == '__main__':
sys.exit(main("fixes"))
def ten2eleven(*files):
"""Convert MDAnalysis 0.10.0 scripts to 0.11.0
Usage:
ten2eleven('myscript.py')
"""
main('MDAnalysis.migration.fixes', ['-w'] + list(fi... |
import json
import logging
from datetime import datetime
from typing import Dict
import pika
from src.data_store.mongo.mongo_api import MongoApi
from src.data_store.redis import Keys
from src.data_store.stores.store import Store
from src.message_broker.rabbitmq.rabbitmq_api import RabbitMQApi
from src.utils.constants... |
import unittest
from api.exceptions import (
DuplicateMemberException,
TooFewMembersException,
TooManyMembersException,
)
from api.models import (DraftPick, Pool)
from django.contrib.auth.models import User
from django.test import TestCase
# TODO(shravan): Figure out how to run these tests in the django
# unit... |
import logging
from .version import __version__
from .sendgrid import SendGridClient
from .exceptions import SendGridError, SendGridClientError, SendGridServerError
from .message import Mail
from credentials import *
def send_via_sendgrid(
receiver, subject, html=None,
plain_text=None, from_name=FROM_... |
class AternosError(Exception):
pass
class AternosCredentialsError(AternosError):
pass
class AternosServerStartError(AternosError):
pass
class AternosIOError(AternosError):
pass
class CloudflareError(AternosError):
pass
|
import errno
import os
import sys
from setuptools import setup, find_packages
from setuptools.command.install import install
from hendrix import __version__
def file_name(rel_path):
dir_path = os.path.dirname(__file__)
return os.path.join(dir_path, rel_path)
def read(rel_path):
with open(file_name(rel... |
#
# Copyright 2018 Dynatrace 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
#!/usr/bin/env python
################################################################################
# This script generate random stimuli for single-population BCPNN network.
################################################################################
import os
import sys
import re
import math
import random
f... |
import numpy as np
import copy
from collections import OrderedDict
from park import core, spaces, logger
from park.param import config
from park.utils import seeding
from park.utils.ordered_set import OrderedSet
from park.utils.directed_graph import DirectedGraph
from park.envs.spark_sim.action_map import compute_act_... |
def binary_search(lo, hi, condition):
"""TODO - add docs"""
while lo <= hi:
mid = (lo + hi) // 2
result = condition(mid)
if result == 'found':
return mid
elif result == 'left':
hi = mid - 1
else:
lo = mid + 1
return -1
|
# -*- coding: utf-8 -*-
from django.db import models
class TimeModelMixin(models.Model):
"""Model内时间维护信息插件
注意!!:因为此mixin继承自models.Model,所以子类在继承时要确保此mixin在models.Model`出现`之前使用,
否则会出现method resolution order (MRO) 报错"""
created_time = models.DateTimeField("创建时间", auto_now_add=True, editable=False)
l... |
from tempfile import NamedTemporaryFile
from shell_utils import run_command
import sys
import os
import json
import re
import sys
def run_airbnb_spider(**kwargs):
print("Starting scraper {}".format(kwargs))
results = run_spider("scrapers/bnbdata/spiders/airbnb.py", **kwargs)
clean_results = []
for resu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.