content stringlengths 5 1.05M |
|---|
import os
import json
import pytest
from click.testing import CliRunner
from skedulord.common import HEARTBEAT_PATH
from skedulord.web.app import create_app
from skedulord.cli import history, summary, version
from skedulord import version as lord_version
@pytest.fixture()
def clean_start_small():
os.system("lor... |
from itertools import cycle
class DummySsmClient:
def __init__(self):
self.__dummy_params = cycle([
{
'Name': 'TestParameter',
'Type': 'String',
'Value': 'StringValue1',
'Version': 10,
},
{
... |
from typing import Dict
from types import FunctionType
routes: Dict[str, FunctionType] = {}
def add(path: str, method: str) -> FunctionType:
def update(func: FunctionType) -> FunctionType:
global routes
routes[path.upper()+method.upper()] = func
return func
return update |
# coding=utf-8
"""BinaryNet implemented in Keras."""
import keras
from scripts.ann_architectures.BinaryConnect import binarization
# This class extends the Lasagne DenseLayer to support BinaryConnect
class Dense(keras.layers.Dense):
"""Binary Dense layer."""
def __init__(self, num_units, binary=True, stoc... |
#!/usr/bin/env python
""" A unittest script for the MIMS module. """
import unittest
from cutlass import MIMS
class MimsTest(unittest.TestCase):
""" Unit tests for the cutlass MIMS class. """
def testRequiredFields(self):
""" Test the required_fields() static method. """
required = MIMS.req... |
#!/usr/bin/env python
import argparse
from pathlib import Path
import numpy as np
from tqdm import tqdm
from carla_constants import *
def make_spherical_lut(lut_file, output_width, output_height):
lutx = np.zeros((output_height, output_width))
luty = np.zeros((output_height, output_width))
depth_multipl... |
# Simple neural network with multiple inputs numpy code
import numpy as np
weights = np.array([0.1, 0.2, 0])
def neural_network(input, weights):
pred = input.dot(weights)
return pred
toes = np.array([8.5, 9.5, 9.9, 9.0])
wlrec = np.array([0.65, 0.8, 0.8, 0.9])
nfans = np.array([1.2, 1.3, 0.5, 1.0])
input =... |
""" File: P1_utility_functions.py
Utility functions used in Phase 1 Pre-processing of the raw chat (.csv) file
"""
import os.path
import re
import nltk
import gensim
from nltk.stem import WordNetLemmatizer
def getStopWords(stopWordFileName):
"""Reads stop-words text file which is assumed to have o... |
from __future__ import absolute_import
from .startup import set_line, set_teams, set_draft, draft
from .reporting import standings
from .utils import *
from .config import *
__all__ = ['startup', 'reporting', 'utils', 'config']
|
from discord.ext import commands
from .responder import ButtonResponse, SelectMenuResponse
class ComponentCog(commands.Cog):
def __init__(self, bot):
global Guild_settings, Texts
global get_txt
self.bot = bot
@commands.Cog.listener()
async def on_socket_response(self, pl):
... |
#!/usr/bin/env python3
# This is free and unencumbered software released into the public
# domain.
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a
# compiled binary, for any purpose, commercial or non-commercial, and
# by any means.
# I... |
# -*- coding: utf-8 -*-
from elasticsearch import Elasticsearch, ImproperlyConfigured
from elasticsearch_dsl import Search
from rest_framework import viewsets
from rest_framework_elasticsearch import es_views, es_filters
from api.pagination import (
LargeResultsSetPagination,
SmallResultsSetPagination
)
from a... |
"""Module for interacting with Evergreen."""
import logging
from copy import deepcopy
from dsi.evergreen import helpers
DEFAULT_EVERGREEN_URL = "https://evergreen.mongodb.com"
"""The default Evergreen URL."""
class EvergreenError(Exception):
"""Generic class for Evergreen errors."""
class Empty(EvergreenErr... |
from __future__ import print_function
import os
import cv2
import pickle
import gzip
import numpy as np
from retinaface import RetinaFace
thresh = 0.7
flip = False
im_scale = 0.5
img_dir = "pic"
gpuid = 0
detector = RetinaFace('./model/R50', 0, gpuid, 'net3')
data = []
img_list = os.listdir(img_dir)
img_list.sort(key... |
import os
USER_HOME = os.getenv("HOME")
# index dir
index_sent_cache_dir = USER_HOME + "/a_path_to"
# concpet net
conceptnet_dir = USER_HOME + "/a_path_to"
rel2idx_path = os.path.join(conceptnet_dir, "assertions.csv_en.csv_rel2idx.txt")
triplet2template_path = os.path.join(conceptnet_dir, "template.json")
# raw cor... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from object import Object
from separator import Separator
from size import Size
from objects import *
class Box(Object):
"""This class represents a box"""
__name__ = "Box"
def __init__(self):
Object.__init__(self)
self.separators = list()
d... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#!/usr/bin/python
import json
import tempfile
import subprocess
import re
import os
import shutil
import sys
from pprint import pprint
mypwd = os.getcwd()
tempdir = tempfile.mkdtemp()
os.chdir(tempdir)
#TODO change to variable
url=sys.argv[1]
json_data = subprocess.check_output(["youtube-dl","-j",url])
metadata = j... |
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
__all__ = [x.replace('.py', '') for x in os.listdir(dir_path) if
x.endswith('.py') and x != '__init__.py']
|
import asyncio
from unittest import mock
def async_mock(*args, **kwargs):
m = mock.MagicMock(*args, **kwargs)
async def mock_coro(*args, **kwargs):
return m(*args, **kwargs)
mock_coro.mock = m
return mock_coro
def async_test(coro):
def wrapper(*args, **kwargs):
loop = asyncio.... |
# https://pythonhosted.org/setuptools/setuptools.html#namespace-packages
# __import__('pkg_resources').declare_namespace(__name__)
import mapzen.whosonfirst.pip
import mapzen.whosonfirst.placetypes
import shapely.geometry
import logging
def reverse_geocoordinates(feature):
props = feature['properties']
lat ... |
import argparse
import os
import time
from os import path
import hashlib
from dateutil.parser import isoparse
import jsonpickle
import datetime
import json
from core_data_modules.cleaners import swahili, Codes
from core_data_modules.traced_data import Metadata, TracedData
from core_data_modules.traced_data.io import T... |
#!/usr/bin/env python3
################################################################################
#
# <PROJ> Create repo labels
# <FILE> make_repo_labels.py
# <AUTH> Benjamin Skinner (btskinner@virginia.edu)
# <INIT> 19 November 2018
#
##############################################################################... |
version = "2018-01-29" |
from django.urls import path
from atlassian_jwt_auth.frameworks.django.tests import views
urlpatterns = [
path('asap/expected', views.expected_view, name='expected'),
path(r'^asap/unexpected', views.unexpected_view, name='unexpected'),
path('^asap/decorated', views.decorated_view, name='decorated'),
... |
"""This is rc-update support."""
__revision__ = '$Revision$'
import os
import Bcfg2.Client.Tools
import Bcfg2.Client.XML
class RcUpdate(Bcfg2.Client.Tools.SvcTool):
"""RcUpdate support for Bcfg2."""
name = 'RcUpdate'
__execs__ = ['/sbin/rc-update', '/bin/rc-status']
__handles__ = [('Service', 'rc-upd... |
'''调度器'''
from .Process import ProcessPool
from .Thread import ThreadMap, ThreadPool, Thread
from .Asyncio import Gevent, Asyncio
from .typing import Union, Callable, RunCalculation, RunIOintensive, RunTask
from .Communication import broadcast, Processbroadcast, asyncbroadcast, Lock
from .publictool import task... |
import sys, requests, getpass, json, argparse, re
class FFSQuery:
"""
FFSQuery provides a wrapper for creating FFS queries and returning results
The FFS Query class provides a number of methods for logging into Code42, building a query,
and conducting a search
"""
def __init__(self, base_url)... |
import json
import requests
def getStatusByName(data, name):
try:
return filter(lambda x: x['name'] == name, data['sensors']['door_locked'])[0]['value']
except KeyError:
return true
def getDoorstatus():
resp = requests.get(url="http://realraum.at/status.json")
data = resp.json()
... |
"""Script used to estimate discovery potential quickly. It uses some pretty
absurd approximations, but is REALLY REALLY fast (equivalent or faster than a
single trial, and is good to within ~30-50%). Use with some caution to
quickly guess appropriate flux scales, or understand trends, without full
calculations.
"""
imp... |
import unittest
# Can't use from... import directly since the file is into another folder
import os, sys
from os.path import dirname, join, abspath
sys.path.insert(0, abspath(join(dirname(__file__), '..')))
from warmup.repeatedString import NewString
class TestRepeatedString(unittest.TestCase):
def setUp(self):... |
from auto_schema.replica_set import ReplicaSet
dc = 'eqiad'
section = 's5'
# Don't add set session sql_log_bin=0;
command = 'REVOKE DROP ON \\`%wik%\\`.* FROM wikiadmin@\'10.%\';'
# DO NOT FORGET to set the right port if it's not 3306
replicas = None
replica_set = ReplicaSet(replicas, section, dc)
replica_set.sql_on... |
import numpy as np
import math
from scipy.linalg import lu, qr, solve_triangular, inv, solve, svd
from numpy.linalg import cond
from numalgsolve.polynomial import Polynomial, MultiCheb, MultiPower, is_power
from scipy.sparse import csr_matrix, vstack
from numalgsolve.utils import Term, row_swap_matrix, clean_zeros_from... |
from torch import nn
from detectron2.layers import Conv2d
from .partialconv2d import PartialConv2d
from .deform_conv import DFConv2d
from detectron2.layers.batch_norm import get_norm
import spconv
from spconv import ops
import spconv.functional as Fsp
import pdb
# from spconv import ops, SparseConvTensor
class Spars... |
#!/usr/bin/env python
from __future__ import print_function
from sys import argv, exit
from os.path import join, exists
from numpy import array,genfromtxt,atleast_2d
from numpy.linalg import norm
def extract_eigvals(folder):
'''
Reads eigvals.dat in folder and extracts raw data as a
two-dimensional array... |
# """
# ckwg +31
# Copyright 2020 by Kitware, Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice,
# this list of con... |
import librosa.display
import matplotlib.pyplot as plt
import json
import torch
import torchaudio
import hifigan
def manual_logging(logger, item, idx, tag, global_step, data_type, config):
if data_type == "audio":
audio = item[idx, ...].detach().cpu().numpy()
logger.add_audio(
tag,
... |
from syned.beamline.beamline_element import BeamlineElement
from wofrywise2.beamline.wise_optical_element import WiseOpticalElement
class WiseBeamlineElement(BeamlineElement):
def __init__(self, optical_element=WiseOpticalElement()):
super(WiseBeamlineElement, self).__init__(optical_element=optical_eleme... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Author: Andrey Skopenko <andrey@scopenco.net>
'''
This module is a set of funcs and classes
for ispmanager plugin creation.
'''
# configs
LOG_FILE = '/usr/local/ispmgr/var/ispmgr.log'
from os import getpid
from xml.dom import minidom
class ExitOk(Exception):
pass
... |
def algo_AES(string, do, key):
# IMPORTS
import base64
try:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.fernet import Fernet
e... |
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
class BlogApphook(CMSApp):
name = _("Blog Apphook")
urls = ["cmsplugin_blog.urls"]
apphook_pool.register(BlogApphook) |
"""
Module for Serialization and Deserialization of a KNX Disconnect Request information.
Disconnect requests are used to disconnect a tunnel from a KNX/IP device.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from xknx.exceptions import CouldNotParseKNXIP
from .body import KNXIPBody
from ... |
print("Hello World!")
print("I'm modiftying this file and pushing it")
print("done the changes")
|
# Face detection by Dlib
## Dlib installation steps
# 1. brew install boost
# 2. brew install boost-python
# 3. Install XQuartz-2.7.9
# sudo ln -s /opt/X11/include/X11 /usr/local/include
# 4. Download dlib
# cd dlib-18.18/
# sudo python setup.py install
#
# Running samle
# a. pip install scikit-image
# b. Dow... |
"""SoulfulArt_Platform URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')... |
import pytest
def test_index(client):
response = client.get('/api/')
# print(response.json)
assert response.json == {
'links': 'http://127.0.0.1:5000/api/links', 'users': 'http://127.0.0.1:5000/api/users', 'tags': 'http://127.0.0.1:5000/api/tags'}
|
try:
import drawBot as db
except:
pass
from coldtype.pens.draftingpen import DraftingPen
from coldtype.pens.draftingpens import DraftingPens
from coldtype.geometry import Rect, Edge, Point
from coldtype.pens.drawablepen import DrawablePenMixin
from coldtype.color import Color, Gradient
def get_image_rect(src... |
from bs4 import BeautifulSoup
import requests
source = requests.get('https://www.indeed.com/jobs?q=python+developer&l=').text
soup = BeautifulSoup(source,'html5lib')
for jobs in soup.find_all (class_='result'):
try:
title = jobs.h2.text.strip()
except Exception as e:
title = None
print(... |
#!/usr/bin/env python
"""
CLASS imu_visualizer
purpose:
- Class definition of 'IMUVisualizer' to be used in Visualizer node
"""
# essential modules
import numpy as np
import math
import rospy
import tf_conversions
import tf2_ros
import geometry_msgs.msg
from sensor_msgs.msg import Temperature, Imu
from... |
import pytest
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
def f():
raise SystemExit(1)
def test_runner():
with pytest.raises(SystemExit):
f()
|
#coding=utf-8
'''
Created on 2016-1-18
@author: Devuser
'''
from django import template
from doraemon.auth_extend.user.templatetags.auth_required_node import LogoutRequiredNode,LoginRequiredNode,UserRequiredNode,ManagerRequiredNode,AdminRequiredNode
register = template.Library()
@register.tag()
def admin_required... |
import Blender
from Blender import *
import Blender
RotationMatrix= Blender.Mathutils.RotationMatrix
MATRIX_IDENTITY_3x3 = Blender.Mathutils.Matrix([1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0])
def eulerRotateOrder(x,y,z):
x,y,z = x%360,y%360,z%360 # Clamp all values between 0 and 360, values outside th... |
from __future__ import absolute_import
from keras import regularizers
from keras.regularizers import l1,l2,l1_l2
from keras.utils import multi_gpu_model
from keras.models import Sequential, Model
from keras.layers import Input, Dropout, Concatenate, Embedding, concatenate
from keras.layers import Dense, Bidirectional, ... |
import torch
import torch.nn as nn
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
# Class id to name mapping
COCO_INSTANCE_CATEGORY_NAMES = [
'__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat', 'traffic ligh... |
#
# Copyright 2012-2014 John Whitlock
#
# 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 writ... |
import logging
import pandas as pd
import time
from quartic_sdk.model.BaseQuarticModel import BaseQuarticModel
from quartic_sdk.utilities import constants
class SupportedModel(BaseQuarticModel):
"""
Example Model used for testing model
This is a valid model that can be save to quartic platform
"""
... |
import requests
import json
from flask import Blueprint, request
from responses import Result, ServerErrorResult, InvalidParameterResult
_user = Blueprint('_user', __name__, template_folder='templates')
cloud = Blueprint('_user', __name__, url_prefix='/api/login')
@_user.route('/', methods=['POST'])
def api_login(... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: ESToCSV.py
Description : 从es中导出数据到csv,构建知识库
Author : charl
date: 2018/12/12
-------------------------------------------------
Change Activity: 2018/12/12:
----------------------------------------... |
"""
workflows of AiiDA-KKR
"""
# import all workflows here to expose them in `aiida_kkr.workflows` directly
from .voro_start import kkr_startpot_wc
from .dos import kkr_dos_wc, parse_dosfiles
from .kkr_scf import kkr_scf_wc
from .eos import kkr_eos_wc, rescale, get_primitive_structure
from .gf_writeout import kkr_flex... |
class LinearAveragesService:
def __init__(self, dataset):
self.dataset = dataset
def call(self):
averages = {}
counts = {}
for row in self.dataset:
# Get the class of this point
cl = row.match
averages.setdefault(cl, [0.0] * (len(row.data))... |
import base64
import random
from django.contrib.admin.sites import AdminSite
from django.contrib.admin.views.main import IS_POPUP_VAR
from django.contrib.contenttypes.models import ContentType
from django.contrib.messages.storage.fallback import FallbackStorage
from django.core.files.uploadedfile import SimpleUploaded... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-08-29 08:05
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cms', '0018_add_group_permissions'),
]
operations = [
migrations.AlterModelOptions(... |
import kass_nn.level_2.characteristics.min_vs_long_req as long
if __name__ == '__main__':
long.main("BIG_TEST_TRANS_min_long.log") |
import tensorflow as tf
import modules
import math
class CrazyCluster(modules.BaseModule):
def __init__(self, feature_size, hidden_size, num_frames, last_layer, num_cluster, do_shift=True):
self.feature_size = feature_size
self.num_frames = num_frames
self.hidden_size = hidden_size
... |
import pyperclip
import json
from tkinter import *
from tkinter import messagebox
from password_gen import generate_password
# ---------------------------- PASSWORD GENERATOR ------------------------------- #
def gen_password():
password = generate_password()
inp_password.delete(0, END)
inp_password.insert... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@file createNet.py
@author Michael Behrisch
@author Daniel Krajzewicz
@date 2008-07-04
@version $Id$
Create the XML input files for the generation of the SUMO network
of the CityMobil parking lot.
SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
Cop... |
# Import modules
import numpy as np
import pandas as pd
from pandas_profiling import ProfileReport
print("Setup Complete")
# Load the data from the tsv file in a dataframe
file_path = "/home/apprenant/simplon_projects/foodflix/data/01_raw/en.openfoodfacts.org.products.tsv"
df = pd.read_csv(file_path, sep='\t')
# Take... |
from __future__ import absolute_import
from ... import wesanderson as wap
def test_print_maps(capsys):
wap.print_maps()
out, err = capsys.readouterr()
lines = out.split('\n')
assert lines[0] == 'Aquatic1 qualitative 5'
def test_get_map():
palette = wap.get_map('cavalcanTi')
ass... |
import tensorflow as tf
from grace_dl.tensorflow import Compressor
class FP16Compressor(Compressor):
"""Compress all floating point gradients to 16-bit."""
def compress(self, tensor, name):
"""Downcasts the tensor to 16-bit."""
tensor_compressed = tensor
if tensor.dtype.... |
"""
Tests for the coord module
"""
import os
import sys
import pytest
# Add our folder to the system path so python can find our code.
current_location = os.path.dirname(__file__)
sys.path.append(os.path.join(current_location, '..'))
from mcsim.coordinates import calculate_distance
def test_calculate_distance():
... |
from __future__ import annotations
from app.constants import WINWIDTH
from app.engine import engine
from ..ui_framework import HAlignment, UIComponent
from ..ui_framework_layout import ListLayoutStyle, UILayoutType
from ..ui_framework_styling import UIMetric
from .text_component import TextComponent
class IconRow(UI... |
import logging
from pathlib import (
Path,
)
import coloredlogs
import jinete as jit
level = logging.INFO
logging.basicConfig(level=level)
coloredlogs.install(level=level)
logger = logging.getLogger(__name__)
BASE_PATH = Path(__file__).parents[2]
DATASETS_PATH = BASE_PATH / "res" / "datasets"
def main():
... |
import tensorflow as tf
a = tf.constant(5)
b = tf.constant(2)
c = tf.constant(3)
d = tf.multiply(a, b)
e = tf.add(c, b)
f = tf.subtract(d, e)
# NOTE: Opening a session using the with clause will ensure the session is
# automatically closed once all computations are done.
with tf.Session() as sess:
fetches = [a, ... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
import numpy
import torch
from torch import nn
from maskrcnn_benchmark.structures.bounding_box import BoxList
from .roi_mask_feature_extractors import make_roi_mask_feature_extractor
from .roi_mask_predictors import make_roi_mask_predic... |
# -*- coding:utf-8 -*-
import tensorflow as tf
import time
from tensorflow.examples.tutorials.mnist import input_data
import mnist_inference
import mnist_train
EVAL_INTERVAL_SECS = 10
def evaluate(mnist):
x =tf.placeholder(
tf.float32,
[None,mnist_inference.INPUT_NODE],
name = 'x-input')... |
import re
import requests
from bs4 import BeautifulSoup
#Default reddit URLs look like this.
_reddit_url = re.compile(r'http(s)?://(www.)?reddit.com/r/learnprogramming')
def getURL(url):
assert _reddit_url.match(url)
headers = {'User-Agent': 'Tarunz Reddit Search bot version 1.0'}
r = requests.get(url, headers =... |
"""
**************************************************************************
\file read_brdf.py
\author Alejandro Sztrajman
\date March 2018
\version 1.00
Script for the UTIA BRDF data loading and value interpolation
################################################################
run using:
python read_b... |
# coding:utf-8
#!/usr/bin/python
#
# Copyright (c) Contributors to the Open 3D Engine Project.
# For complete copyright and license terms please see the LICENSE at the root of this distribution.
#
# SPDX-License-Identifier: Apache-2.0 OR MIT
#
# -- This line is 75 characters -------------------------------------------
... |
y = x[0, ..., 2]
|
__version__ = '0.2.4'
from .scraper import Scraper # noqa: F401
|
import os
import cv2
from paddle.v2.image import load_image
class DataGenerator(object):
def __init__(self, char_dict, image_shape):
'''
:param char_dict: The dictionary class for labels.
:type char_dict: class
:param image_shape: The fixed shape of images.
:type image_sha... |
import abc
from typing import Optional
class PluginInstaller(abc.ABC):
"""
Implements installation functionality for
"""
def setup(self) -> None:
"""
Perform any necessary setup before installing plugins
"""
def teardown(self) -> None:
"""
Tear down any re... |
import sys
sys.path.append("../")
from api.metrics.rent_burdened import RentBurdenedMetrics
from api.utils.testing import create_test_db
...
def test_RBU():
rent_burdened_households_table = [
{
"area_number": 1,
"period_end_year": 2019,
"segment": "all",
"v... |
#! /usr/bin/env python
from gazebo_msgs.srv import GetModelState
import rospy
from gazebo_msgs.msg import ModelStates
from geometry_msgs.msg import Pose
class Block:
def __init__(self, name):
self._name = name
class Robot:
def __init__(self, number, x, y, z):
self.name = number
self.... |
from django.shortcuts import render
from django.shortcuts import redirect
from .forms import BookForm, ChangePassword, DeleteAccount, FutureBook
from .settings import validate_password, change_password, delete_account
from .drones import get_vehicles_of_user, get_all_drone_data, get_all_base_data, form_time, get_future... |
#!/usr/bin/env python3
#homework5 - Advanced
import matplotlib.pyplot as plt
import pandas as pd
def printme(name, to_print):
print(f'{name}:')
print(f'{to_print}\n\n')
insurance = pd.read_csv('data/insurance.csv')
printme("insurance dataframe", insurance.to_string())
printme("insurance dataframe", insuranc... |
from tilepack.outputter.mbtiles import MbtilesOutput
from tilepack.outputter.zipfile import ZipfileOutput
from tilepack.outputter.null import NullOutput
|
#!/usr/bin/python
#
## mrquery
##
## This program provides an interface to send arbitrary queries to Moira.
#
import common
import re, argparse, json
import pymoira
class QueryInfo:
def __init__(self, name):
info, = client.query('_help', (name,))
# FIXME: the format Moira server uses is horribl... |
#!/usr/bin/env python
import os
import requests
from bs4 import BeautifulSoup
import json
import random
class Quotes:
def __init__(self):
if os.path.isfile('quotes.json'):
with open('quotes.json', 'r') as fin:
self.quotes = json.load(fin)
else:
self.quotes ... |
# 3. With a given integral number n, write a program to generate a dictionary that contains (i, i x i)
# such that is an integral number between 1 and n (both included). and then the program
# should print the dictionary.Suppose the following input is supplied to the program: 8
# Then, the output should be: {1: 1, 2: 4... |
import hashlib
import json
import os
import signal
import subprocess
import time
from contextlib import contextmanager
from typing import List, Set
import requests
def getDefaultExpectedHash() -> bytes:
# "uniquestring" is stored in /etc/unique of the SSH server. We then run
# the command `sha1sum /etc/uniqu... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import keras
import numpy as np
import warnings, os, sys
from keras.models import Model
from keras import initializers, regularizers, constraints
from keras.utils import conv_utils
from keras.utils.data_utils i... |
from onesignal_sdk.response import OneSignalResponse
from .mocks import MockHttpxResponse
class TestOneSignalResponse:
def test_sets_body_and_status_code(self):
http_response = MockHttpxResponse(201, {'created': True})
response = OneSignalResponse(http_response)
assert response.status_co... |
import pandas
user_df = pandas.read_csv('processed_data/prj_user.csv')
ids = user_df["id"]
ids = list(ids.values)
error_ids= []
for i, id in enumerate(ids):
try:
int(id)
except:
error_ids.append(i)
user_df = user_df.drop(user_df.index[error_ids])
user_df.to_csv("processed_data/prj_user.cs... |
import gc
from twisted.trial.unittest import TestCase
from axiom.store import Store
from axiom.upgrade import registerUpgrader, registerAttributeCopyingUpgrader
from axiom.item import Item, declareLegacyItem
from axiom.attributes import integer, reference
from axiom.errors import BrokenReference, DeletionDisallowed
... |
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: vraj@reciprocitylabs.com
# Maintained By: vraj@reciprocitylabs.com
from ggrc import db
from .mixins import Identifiable, created_at_args
class Ev... |
# Try and Except Blocks
Example 1
Input: 5 / 0
result = 5 / 0
print(result)
# Example 2
try:
result = 5 / 0
print(result)
except ZeroDivisionError:
print("Cannot divide by zero")
# Example 3
try:
print(unknown_variable)
except NameError as error:
print("An error occurred, this is the detailed err... |
from rest_framework import routers
from libs.components.permissions.resources import AppResources
from library.v1 import views as library_views
# Declare version 1 resources for our app 'library'
app_resources = AppResources(1, 'library')
create_resource = app_resources.create_resource
# Define a resource for books... |
from functools import wraps
from flask import request, jsonify, abort
from app import app
def check_key(key, ip):
"""
Summary: Check API Key and IP.
Author: Hans Husurianto
@param key: API Key to check.
@param ip: IP of the requester.
@return: boolean
"""
if key is None or... |
import numpy as np
import cv2
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from numpy import dot, sqrt
from numpy.linalg import norm, inv
from scipy.optimize import least_squares
from scipy.optimize import minimize
from scipy.linalg import rq
from src.sfm_pipeline.axis_angle import (rotation... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.