content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
from rest_framework.documentation import include_docs_urls
import notifications.urls
urlpatterns = [
path(r'', include('rbac.urls')),
path(r'', include('cmdb.urls')),
path(r'', include('rmms.url... | python |
# Copyright 2018-2021 Jakub Kuczys (https://github.com/jack1142)
#
# 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 app... | python |
import logging
import os
import numpy as np
from .siamese_net import DNN
logger = logging.getLogger(__name__)
package_directory = os.path.dirname(os.path.abspath(__file__))
similarity_model_pretrained = os.path.join(package_directory, "model")
class SimilarityModel:
def __init__(self):
self.model = Non... | python |
from __future__ import annotations
from yarl import URL
import io
import typing
import os
from .factory import construct_repr
if typing.TYPE_CHECKING:
from .factory import HttpHandler
__all__ = ("Image",)
class Image:
"""
A class representing an `Image`.
Attributes:
url (str): URL of the... | python |
import logging
import enum
import copy
import telegram.error
from telegram import (
InlineKeyboardButton,
InlineKeyboardMarkup,
ParseMode
)
from app.entities import KnowledgeStatus
from app.card import Card
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level... | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import socket
default_port = 8003 # default port when adding a new server
listen_port = 8003 # server listens on this port
my_address = [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]
if not ip.startswith("1.")][0]
dns_module_listen_port = 800... | python |
import datetime
import logging
from django.core.management.base import BaseCommand
from django.db import connection, transaction
from framework.celery_tasks import app as celery_app
logger = logging.getLogger(__name__)
TABLES_TO_POPULATE_WITH_MODIFIED = [
'addons_zotero_usersettings',
'addons_dropbox_userset... | python |
#!/usr/bin/env python
#Makes the output file "grid" which is used in various postprocessing scripts
import argparse
import numpy as np
import sys
import os
import re
# parse command line options
parser = argparse.ArgumentParser(description="Generates a cartesian mesh with a uniform region surrounded by a stretched gri... | python |
"""
App entry point which register FastAPI routers.
More info about used app structure: https://fastapi.tiangolo.com/tutorial/bigger-applications/
If you want to create a new API endpoint add endpoint handler to existed router or
create a new module in `routes` directory.
"""
from fastapi import FastAPI
from fastapi.... | python |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
from matplotlib import cm
from scipy.interpolate import interp1d
from scipy.spatial import distance
from scipy.optimize import differential_evolution
CELL_INFO_DIR = os.path.join('data-share', 'raw', 'cell_info')
def blend_electrodes(el... | python |
#!/usr/bin/env python
from distutils.core import setup
setup(name = "ciscotropo-webapi-python",
version = "0.1.4",
url = "http://github.com/tropo/tropo-webapi-python",
maintainer = "Cisco",
maintainer_email = "support@tropo.com",
description ... | python |
from heuslertools.tools.measurement import Measurement
import xrayutilities as xu
import warnings
import numpy as np
class RSMMeasurement(Measurement):
"""Object representing rsm measurement.
Parameters
----------
file : str
path of xrdml file.
Attributes
----------
en : str
... | python |
import numpy as np
import numpy.linalg as la
def gaussian_estimate(data, label, alpha):
assert len(data) == len(label), "label length mismatch"
assert label.min() == 0, "label should start from 0"
assert label.max() != 0, "label should have multiple"
trim = np.sum(data, axis=0) > 0
data = data[:, ... | python |
#
# 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, software
# ... | python |
# coding=utf-8
"""
Default Django settings for all Work4 projects.
Your own app should import all attributes from this file.
"""
from __future__ import unicode_literals
import os
import sys
from tzlocal import get_localzone
def env_to_bool(val):
"""Use this when parsing environment variables for booleans as ... | python |
""" This will module contains the setup_flask function as well as registry functions """
__author__ = 'Ben Christenson'
__date__ = "9/15/15"
import os
import inspect
import sys
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import flask_login
from flask_login import LoginManager
from flask.blueprints ... | python |
import wasm3 as m3
import pytest
from helpers import wat2wasm
MV_SWAP_WASM = wat2wasm("""
(module
(func (export "swap") (param i32 i32) (result i32 i32)
(get_local 1)
(get_local 0)
)
)
""")
MV_IMPORT_WASM = wat2wasm("""
(module
(type $t0 (func (param i32 i64) (result i64 i32)))
(import "env" "swap" (... | python |
""" # lint-amnesty, pylint: disable=cyclic-import
XFields for video module.
"""
import datetime
from xblock.fields import Boolean, DateTime, Dict, Float, List, Scope, String
from xmodule.fields import RelativeTime
# Make '_' a no-op so we can scrape strings. Using lambda instead of
# `django.utils.translation.ug... | python |
"""Ingest by directly writing a ZIP file to archive storage.
"""
from __future__ import print_function
import sys
import os
import os.path
import re
import time
from threading import Thread
if sys.version_info < (3, 0):
import Queue as queue
else:
import queue
import zlib
import logging
import pytest
import ic... | python |
from rest_framework import permissions
class UpdateOwnProfile(permissions.BasePermission):
def has_object_permission(self,request,view,obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.id==request.user.id
class UpdateStatus(permissions.BasePermission):
de... | python |
import collections
import logging
import string
from abc import abstractmethod
from typing import Callable, List
from flask_sqlalchemy import SQLAlchemy
from retrying import retry
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm.exc import FlushError, NoResultFound
from profiles.exceptions import OrcidTo... | python |
from .common import EWSAccountService, create_attachment_ids_element
from ..properties import RootItemId
from ..util import create_element
class DeleteAttachment(EWSAccountService):
"""MSDN:
https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/deleteattachment-operation
"""
... | python |
"""
388. Longest Absolute File Path
Medium
Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:
Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2. subdir1 contains a file file1... | python |
# -*- coding: utf-8 -*-
# DO NOT EDIT THIS FILE!
# This file has been autogenerated by dephell <3
# https://github.com/dephell/dephell
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
readme = ""
setup(
long_description=readme,
name="tgintegration",
version=... | python |
import logging
from datetime import datetime
import tweepy
import creds
from main import make_covid_graph
logging.basicConfig(filename='nepal-covid.log',
level=logging.INFO,
format='%(asctime)s-%(name)s - %(levelname)s - %(message)s',
datefmt='%d-%b-%y %H... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
test_compat.py
Last updated: 2019-09-27
"""
from wz_core.reporting import Report
from test_core import testinit, runTests
if __name__ == '__main__':
testinit ()
# from wz_compat import migrate
# runTests (migrate)
# from wz_compat import import_pup... | python |
import base64
import logging
from tornado.escape import json_decode
from tornado.web import Finish
from db import UserStatus
from emailer import send_verification_email, send_password_reset_email
from service.property import get_property, set_property
from service.user import (
get_user,
get_user_profile,
... | python |
from bs4 import BeautifulSoup
from collections import Counter
from string import punctuation
def word_frequencies(url):
"""
Downloads the content from the given URL and returns a dict {word -> frequency}
giving the count of each word on the page. Ignores HTML tags in the response.
:param url: Full URL ... | python |
import numpy as np
array = np.array([['08', '02', '22', '97', '38', '15', '00', '40', '00', '75', '04', '05', '07', '78', '52', '12', '50', '77', '91', '08'],
['49', '49', '99', '40', '17', '81', '18', '57', '60', '87', '17', '40', '98', '43', '69', '48', '04', '56', '62', '00'],
['81', '49', '31', '73', '55', '79', '... | python |
import os
import logging
import cfn_storage_gateway_provider
import cfn_cache_provider
import cfn_file_share_provider
log = logging.getLogger()
log.setLevel(os.environ.get("LOG_LEVEL", "INFO"))
def handler(request, context):
if request['ResourceType'] == 'Custom::StorageGatewayNfsFileShare':
return cfn_f... | python |
import matplotlib.pyplot as plt
import numpy as np
import numpy.random as random
import re
import textstat
from scipy import stats
from scipy.stats import spearmanr
#coding:utf-8
###############
#一般図書のYL
x = [8, 6.6, 8.5, 6.5, 5, 7, 6, 5, 5, 5, 6.5, 6.5, 7, 8.2, 7.6, 7.5, 7.5, 7.3,
7, 8.2, 8, 8.5, 7, 6.6, 7.7, 7... | python |
import asyncio
from collections import OrderedDict
import logging
import uuid
import msgpack
import re
import types
from wolverine.module import MicroModule
from wolverine.module.controller.zhelpers import unpackb, packb, dump
from wolverine.module.service import ServiceMessage
logger = logging.getLogger(__name__)
c... | python |
"""
Class Encore CIS 211 w/ Joseph
contest.py
Author: Joseph Goh
Updated: 03/04/2021
"""
from typing import List, Dict
class Hometown:
def __init__(self, name: str):
self.name = name
self.champions = []
def get_total_wins(self) -> int:
total = 0
for champ in self.champions:
... | python |
#!/usr/bin/env python3
"""
Copyright (c) 2018 Intel Corporation
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 la... | python |
'''Adapte o código do desafio #107, criando uma função adicional chamada moeda() que consiga
mostrar os números como um valor monetário formatado.'''
import moeda
preco = float(input('Digite o preço: R$ '))
print(f'A metade de {moeda.moeda(preco)} é {moeda.moeda(moeda.metade(preco))}')
print(f'O dobro de {moeda.moeda... | python |
input = open('/Users/krishjain/Desktop/AdventOfCode/Day 6/input.txt', "r").read()
input = input.split("\n\n")
countOfAnswersPerGroup = []
for i in input:
listOfAnswersToWhichAnsweredYes = []
for j in i.replace("\n", ""):
listOfAnswersToWhichAnsweredYes.append(j)
unorderedListOfAnswers = list... | python |
import matplotlib.pyplot as plt
env_map = [(8.92, 283.86), (17.83, 283.44), (68.13, 720.79), (112.8, 892.9), (140.79, 888.92), (101.75, 533.38), (106.89, 478.2), (115.39, 449.42), (117.73, 405.24), (111.25, 342.38), (87.73, 243.69), (113.38, 286.37), (121.92, 281.75), (124.33, 264.21), (124.39, 244.14), (125.74, 228.7... | python |
#
# Copyright (c) 2013-2014 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
import cStringIO
import httplib2
import re
import sys
import fixtures
from inventoryclient import exc
from inventoryclient import shell as inventoryclient_shell
from inventoryclient.tests import utils
from testtools import ... | python |
# coding: utf-8
# http://gitlab.skoltech.ru/shapeev/mlip-dev/blob/master/src/external/python/mlippy/cfgs.py
from __future__ import print_function
import numpy as np
class Cfg:
pos = None
lat = None
types = None
energy = None
forces = None
stresses = None
desc = None
grade = None
def... | python |
from bitrue.client import Client
if __name__ == '__main__':
client = Client(api_key='',
api_secret='',
)
trades = client.get_my_trades()
print(client._order_format_print(trades))
'''
symbol id orderId origClientOrderId price qty comm... | python |
# coding=utf-8
# Copyright 2022 The Balloon Learning Environment Authors.
#
# 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 require... | python |
liste = ["ali", "veli"]
print(liste)
if "al" not in liste:
print("var") | python |
from .optim_low import *
__all__ = ["OptimMP"]
| python |
"""empty message
Revision ID: dcbee03e3639
Revises:
Create Date: 2018-07-10 04:25:35.968792
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'dcbee03e3639'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... | python |
from trezor import wire
from trezor.messages import MessageType
def boot():
# only enable LoadDevice in debug builds
if __debug__:
wire.add(MessageType.LoadDevice, __name__, "load_device")
wire.add(MessageType.ResetDevice, __name__, "reset_device")
wire.add(MessageType.BackupDevice, __name__, ... | python |
from __future__ import print_function
import sys
import os
import requests
from datetime import datetime
from random import randint
import re
class Facegrab:
def __init__(self):
self.base_url = "http://graph.facebook.com/picture?id={}&width=800"
self.sess = requests.Session()
self.sess.hea... | python |
from polygon import WebSocketClient
from polygon.websocket.models import WebSocketMessage
from typing import List
import asyncio
c = WebSocketClient(subscriptions=["T.*"])
async def handle_msg(msgs: List[WebSocketMessage]):
for m in msgs:
print(m)
async def timeout():
await asyncio.sleep(1)
pri... | python |
import numpy as np
#import tensorflow as tf
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from tqdm import tqdm
import argparse
import sys
import cv2
import math
rgb = True
def draw_bboxes (img, boxes, outname):
for i in range(len(boxes)):
xmin,ymin,xmax,ymax,cat = boxes[i]
c... | python |
from pylama_dmypy import VERSION
from setuptools import setup, find_packages
# fmt: off
setup(
name = "pylama-dmypy"
, version = VERSION
, packages = find_packages(include="pylama_dmypy.*", exclude=["tests*"])
, extras_require =
{ 'tests':
[ "pylama==8.3.8"
, "mypy==0.942"
... | python |
# -*- coding: utf-8 -*-
__all__ = ('SlashCommandPermissionOverwriteWrapper', 'SlashCommandWrapper', )
from functools import partial as partial_func
from ...discord.guild import Guild
from ...discord.preconverters import preconvert_snowflake
from ...discord.interaction import ApplicationCommandPermissionOverwrite
UNL... | python |
from collections import deque, defaultdict
import sys
N = int(input())
ab = []
for i in range(N - 1):
ab.append(tuple(map(int, input().split())))
c_list = list(map(int, input().split()))
c_list.sort()
c_que = deque(c_list)
cnt = defaultdict(int)
outs = defaultdict(list)
for a, b in ab:
cnt[a - 1] += 1
cn... | python |
#################################################
# SN74HC595 with software SPI ESP12-E #
# Sums up 1 bit by 1 bit till 255 is reached #
# Author: Miguel Sama #
# Date: 19/06/2018 #
#################################################
from machine import... | python |
#!/usr/bin/env python
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with... | python |
import clr
if clr.use35:
clr.AddReference("Microsoft.Scripting")
clr.AddReference("Microsoft.Dynamic")
clr.AddReference("Microsoft.Scripting.Core")
import Microsoft.Scripting.Ast as Exprs
from Microsoft.Scripting.ComInterop import ComBinder
from Microsoft.Scripting.Utils import (Action, Func)... | python |
import os
import json, boto3
def lambda_handler(event, context):
print("Trigger Event: ")
print(event)
region = os.environ['REGION']
elbv2_client = boto3.client('elbv2', region_name=region)
available_target_groups = os.environ['AVAILABLE_TARGET_GROUPS']
arr_available_target_groups = available_... | python |
import RPi.GPIO as GPIO
import time
pinServo=40
GPIO.cleanup()
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pinServo, GPIO.OUT)
servo=GPIO.PWM(pinServo, 50)
servo.start(0)
while True:
ang = int(input())
# if (ang>170 and ang < 0):
# print('angulo no posible')
# break
# else:
servo.ChangeDutyCycle((ang*12/180))
time.sleep(... | python |
from cdmanager import cd
import os
import shutil
from pathlib import Path
working_folder = '../data/tfs_rep_2/'
destination_folder = '../gemFiles/rep2/'
with cd(working_folder):
for root, dirs, files in os.walk('./'):
#print(dirs)
if 'GEMout' in dirs:
namedir = str(root.replace('./', '... | python |
from __future__ import annotations
import decimal
import re
import pytest
from django.core.validators import MaxValueValidator, MinValueValidator, URLValidator
from rest_framework import serializers
from rest_framework.fields import (
BooleanField,
CharField,
DateField,
DateTimeField,
DecimalField... | python |
from typing import Optional
from pydantic import BaseModel, Field
class ScopeCreate(BaseModel):
scope_name: str = Field(max_length=32)
description: str = Field(max_length=128)
default: Optional[bool] = Field(default=False)
class ScopeUpdate(BaseModel):
description: str = Field(max_length=128)
clas... | python |
def day2_1():
total = 0
for line in open('day2input.txt'):
l, w, h = line.split('x')
l, w, h = int(l), int(w), int(h)
area = 2*l*w + 2*w*h + 2*h*l
slack = min(l*w, w*h, h*l)
total += area + slack
print total
def day2_2():
total = 0
for line in open('day2inpu... | python |
# PROJECT DECEMBRE 2019
# PROJECT STAR MAP / DATABASE
# By Enguerran VIDAL
# This file contains the database handling functions.
###############################################################
# IMPORTS #
#############################################################... | python |
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import pydart
import controller
import numpy as np
import pickle
import action as ac
from numpy.linalg import inv
import mmMath
state = {}
state['DrawAxis'] = True
state['DrawGrid'] = True
state['DrawDataAbs'] = True
state['DrawDataRelGlobal'] ... | python |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from django.conf.urls import include, url
from django.contrib import admin
from gps.view.index import *
urlpatterns = [
url('^getPeople/$', getPeople),
url('^getGPS/$', getGPS),
url('^sendGPS/$', sendGPS),
]
| python |
import csv
import glob
import math
import os
import sys
from random import random, seed
from timeit import default_timer as timer
import time
from statistics import mean
from pathlib import Path
import networkx as nx
import numpy as np
from scapy.layers.inet import IP, UDP
from scapy.utils import PcapWriter, PcapReader... | python |
import os
import sys
import glob
import pickle
import shutil
import argparse
import tensorflow as tf
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def read_pickle_fr... | python |
#!/usr/bin/pyton
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import pdb
import os
directory=os.path.basename(__file__)[:-3]
if not os.path.exists('texFiles/'+str(directory)):
os.system('mkdir texFiles/'+str(directory))
path='texFiles/'+str(directory)
"""
Comparison ... | python |
import logging
from contextlib import closing
from typing import Any, Dict, Optional
from flask_appbuilder.security.sqla.models import User
from flask_babel import gettext as _
from sqlalchemy.engine.url import make_url
from sqlalchemy.exc import DBAPIError, NoSuchModuleError
from rabbitai.commands.base import BaseCo... | python |
"""
Created on Mon Jan 18 12:34:06 2021
Note this is working with ETABs v19, comtypes v1.1.7. It is not working on my local
machiene only on the remote desktop
@author: aguter
"""
import numpy as np
import os
import sys
import comtypes.client
import matplotlib.pyplot as plt
ProgramPath = r"C:\Program Files... | python |
# Copyright (c) 2021, NVIDIA CORPORATION. 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
#
# Unless required by appli... | python |
from unittest import mock
from src.video_player import VideoPlayer
def test_flag_video_with_reason(capfd):
player = VideoPlayer()
player.flag_video("amazing_cats_video_id", "dont_like_cats")
out, err = capfd.readouterr()
lines = out.splitlines()
assert len(lines) == 1
assert "Successfully fla... | python |
from app import db
from app import models
from flask import Blueprint
bp = Blueprint("setup", __name__)
@bp.route("/", methods=["POST"], strict_slashes=False)
def setup():
models.Base.metadata.create_all(db.get_engine())
return "<h1> Created DB successfully! </h1>"
| python |
try:
from setuptools import setup
except ImportError:
print("No setuptools package, using distutils.core")
from distutils.core import setup
import unittest
def my_test_suite():
test_loader = unittest.TestLoader()
test_suite = test_loader.discover('tests', pattern='test_*.py')
return test_suite
setup... | python |
from .compare_gw import * | python |
from django import forms
from django.forms import widgets
from django.utils.translation import ugettext as _
from .models import Organization
from .utils import get_data_source_model
class OrganizationForm(forms.ModelForm):
class Meta:
model = Organization
fields = (
'data_source', '... | python |
import inspect
import sys
import threading
from typing import Callable, Union, TypeVar, Any, Generic, Optional, List, Iterable
class PromiseResolver:
__slots__ = ("_promise", )
def __init__(self, promise):
self._promise = promise
def resolve(self, val):
if self._promise is None:
return
self._promise._re... | python |
from __future__ import annotations
import multiprocessing
import queue
import threading
import time
from dataclasses import dataclass, field
from multiprocessing import Queue, Process
from queue import Empty
from threading import Thread
from typing import List, Dict
import psutil
import requests
from MHDDoS.attack i... | python |
from .convscore_solver import SolverConvScore
import torch
from utils import to_var
from tqdm import tqdm
from math import isnan
import numpy as np
class SolverConvScoreSSREM(SolverConvScore):
def __init__(self, config, train_data_loader, eval_data_loader, is_train=True, model=None):
super(SolverConvScore... | python |
import numpy as np
import cv2 as cv
def cv_imshow(title='Res',img=None):
print(img.shape)
cv.imshow(title,img)
cv.waitKey(0)
cv.destroyAllWindows()
def image_normalization(img, img_min=0, img_max=255):
"""This is a typical image normalization function
where the minimum and maximum of the imag... | python |
# Lint as: python3
# Copyright 2020 DeepMind Technologies Limited. 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
#
# ... | python |
#!/usr/bin/env python
from __future__ import print_function
import math
import rospy
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from b2_logic.nodes.pilot import PilotNode, PVelocityController
from b2.msg import Proximity
DEFAULT_NODE_NAME = "pilot_node"
# Subscribes
DEFAULT_PROXIMITY_TOP... | python |
from aws_cdk import (
aws_s3 as s3,
core
)
class CdkExampleS3Stack(core.Stack):
def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
bucket = s3.Bucket(
self, "mytestbucket",
bucket_name="m... | python |
"""
opencadd.io.core
Defines the base class for the io module.
"""
from pathlib import Path
class _Base:
"""
Base class for io classes.
"""
def __init__(self):
"""
This class contains no __init__ initialization.
"""
raise RuntimeError("This class only support initia... | python |
from django.test import TestCase
from django.template import Template, Context
class TemplateTagTest(TestCase):
def setUp(self):
pass
def test_tag(self):
content = (
"{% load logical_rules_tags %}"
"This is a {% testrule test_is_pizza 'pizza' %}test{% e... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*
import urllib2
import urllib
import cookielib
import re
from config import WEIBO_ACCOUNT, WEIBO_PWD
class Fetcher(object):
def __init__(self, username=None, pwd=None, cookie_filename=None):
self.cj = cookielib.LWPCookieJar()
if cookie_filename is not ... | python |
"""
Pop does not care what it is removing in case of set
Since set is an unordered collection
"""
from prescription_data import patients
trial_patients = {'Denise', 'Eddie', 'Frank', 'Georgia', 'Kenny'}
while trial_patients:
patient = trial_patients.pop()
print(patient, end=':')
prescription = patients[pa... | python |
# Copyright 2016-2017 SAP SE
#
# 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 |
import argparse
import pymongo
import uuid
import datetime
import pprint
import copy
from datetime import timedelta
from starflyer import ScriptBase
from camper.app import markdownify
from logbook import Logger
log = Logger('Migration')
def daterange(start_date, end_date):
for n in range(int ((end_date - start_d... | python |
import json
from datetime import datetime
import time
import PySimpleGUI as sg
import os
import keyring # for password storage
import hashlib
# import all the custom functions
from functionalities import *
# import all the window formats
from windows import *
if __name__ == "__main__" :
# check if... | python |
#To test how fast rotations.py is
from rotations import *
import numpy as np
from timeit import default_timer as timer
ranx5 = np.random.randint(10,size=(100000,3))
ranx6 = np.random.randint(10,size=(1000000,3))
ranx7 = np.random.randint(10,size=(10000000,3))
ranx8 = np.random.randint(10,size=(100000000,3))
start = t... | python |
from os import getenv, getppid, kill, system
from configparser import ConfigParser
from typing import Union, Optional
from psutil import process_iter
from datetime import datetime
from subprocess import Popen
from signal import SIGHUP
from pathlib import Path
from sys import platform
from re import match
from typer im... | python |
import stanza
from stanza.protobuf import DependencyEnhancerRequest, Document, Language
from stanza.server.java_protobuf_requests import send_request, add_sentence, JavaProtobufContext
ENHANCER_JAVA = "edu.stanford.nlp.trees.ud.ProcessUniversalEnhancerRequest"
def build_enhancer_request(doc, language, pronouns_patt... | python |
from .pygbe import *
| 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! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
__... | python |
import carla
from leaderboard.envs.map_utils import *
def viz(args):
client = carla.Client('localhost', 2000)
client.set_timeout(10.0)
world = client.load_world(args.town_name)
carla_map = world.get_map()
spawn_points = carla_map.get_spawn_points()
blueprint_library = world.get_bluepri... | python |
import os
import os.path as path
import shutil
import unittest
from cache import Cache, format_as_timestamp
from pathlib import Path
from datetime import datetime, timedelta
test_folder = 'test-files'
db_file_name = path.join(test_folder, 'test.db')
table_name = 'cache'
folder_path = path.join(test_folder... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0... | python |
import time
import torch
import numpy as np
import pandas as pd
import scipy
from h5py import File
import itertools, random
from tqdm import tqdm
from loguru import logger
import torch.utils.data as tdata
from typing import List, Dict
class TrainHDF5Dataset(tdata.Dataset):
"""
HDF5 dataset indexed by a labels... | python |
import utils.train as train
class DataSet:
def __init__(self, config, problem):
self.config = config
self. problem = problem
self.update()
def update(self):
if not self.config.test:
y_, x_, y_val_, x_val_ = (
train.setup_input_sc(
... | python |
import json
from pathlib import Path
from typing import Dict
import pandas as pd
import sha_calc as sha_calc
from gmhazard_calc.im import IM
from gmhazard_calc import gm_data
class BranchUniGCIM(sha_calc.UniIMiDist, sha_calc.CondIMjDist):
"""Represents the GCIM for a specific IMi and branch
Parameters:
... | python |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.ads.google_ads.v4.proto.resources import campaign_bid_modifier_pb2 as google_dot_ads_dot_googleads__v4_dot_proto_dot_resources_dot_campaign__bid__modifier__pb2
from google.ads.google_ads.v4.proto.services import campaign_bid_... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.