content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015-2018 by Exopy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ---------------... |
from __future__ import absolute_import
from functools import wraps
from testagent.exceptions.SingletonException import SingletonException
__author__ = 'patrizio'
class Singleton(object):
_instances = {}
_configured = False
def __new__(class_, *args, **kwargs):
if class_ not in class_._instances:
... |
from fathom import Point, ORIGIN
from fathom.tikz import Canvas
from fathom.geometry import *
import fathom.tikz.colors as colors
import fathom.tikz.line_styles as line_styles
import fathom.tikz.locations as locations
from itertools import *
if __name__ == '__main__':
canvas = Canvas(
preamble=['\\usepacka... |
#!/usr/bin/python
# coding=utf-8
"""Test suit.""" |
import os
import logging
import copy
from wireless_emulator.clean import cleanup
logger = logging.getLogger(__name__)
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwar... |
from __future__ import annotations
from typing import List
import json
import operator
import random
from logger import logger
from common_utils.check_utils import check_type, check_type_from_list, \
check_file_exists, check_value_from_list
from common_utils.path_utils import get_extension_from_filename
from comm... |
## Installation instructions: https://github.com/nobodysu/zabbix-hardware ##
senderPyPath = r'C:\zabbix-agent\scripts\sender_wrapper.py'
agentConf = r'C:\zabbix_agentd.conf'
senderPath = r'C:\zabbix-agent\bin\win32\zabbix_sender.exe'
## Advanced configuration ##
cmd = ['wmic','BIOS','list','full']
glo... |
import numpy as np
class PivotLines:
def __init__(self, df, params):
"""
numperiod default 288 as testing on 5min and 288 = 12 * 24 5 min periods in a day
"""
self.df = df
self.numPeriods = params["numPeriods"] if "numPeriods" in params.keys() else 288
def run(self... |
import time
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StringType, IntegerType, DoubleType
spark = SparkSession \
.builder \
.appName("PythonSQL") \
.config("spark.yarn.access.hadoopFileSystems", "s3a://demo-aws-2//") \
.getOrCreate()
## Get data from geo location ... |
#!/usr/bin/python
#
# Copyright 2002-2021 Barcelona Supercomputing Center (www.bsc.es)
#
# 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
... |
from flask import Flask, render_template, request
import csv
import random
app=Flask(__name__)
done=set()
name=""
reg=""
filename = "student.csv"
lim=0
exh=""
with open("student.csv") as tempf: lim=len(tempf.read().split("\n"))
lim-=1
totalstu=lim
currstu=0
print("for list of "+str(lim)+" students")
@app.route("/... |
from django.conf.urls import url
from sentences.api.views import (
SentenceAPIView,
SentenceDetailsAPIView,
)
urlpatterns = [
url(r'^$', SentenceAPIView.as_view(), name='sentences'),
url(r'^(?P<pk>[\w.@+-]+)/$', SentenceDetailsAPIView.as_view(), name='sentence-details'),
]
|
def brute_force_root_finder(f, a, b, n):
from numpy import linspace
x = linspace(a, b, n)
y = f(x)
roots = []
for i in range(n-1):
if y[i]*y[i+1] < 0:
root = x[i] - (x[i+1] - x[i])/(y[i+1] - y[i])*y[i]
roots.append(root)
elif y[i] == 0:
... |
from databases import Database
db = Database('sqlite:cars-db.db')
async def get(query, values={}):
rows = await db.fetch_all(query=query, values=values)
dicts = []
for row in rows:
dicts.append(dict(row))
return dicts
async def run(query, values={}):
return await db.execute(query=query, values=values)
... |
# Imports
import tkinter as tk
# Functions
def start():
global score_value
global score
file = open("cookie", "r")
readfile = file.read()
if readfile != "":
score_value = int(readfile)
score.set("Score: " + str(score_value))
file.close()
def on_exit():
file = open("cooki... |
import pygame,random
#Initialize pygame content
pygame.init()
#All keyboard and mouse input will be handled by the following function
def handleEvents():
global awaiting_row, awaiting_col
#Check for new events
for event in pygame.event.get():
#This if makes it so that clicking the X actually closes... |
from django.core.management import BaseCommand
from scheduler.factories import generate_test_data
class Command(BaseCommand):
help = "Populates database with randomly generated data for testing and creates demo accounts."
def add_arguments(self, parser):
parser.add_argument(
"--complicate... |
#!/usr/bin/env python
# pipescaler/termini/__init__.py
#
# Copyright (C) 2020-2021 Karl T Debiec
# All rights reserved.
#
# This software may be modified and distributed under the terms of the
# BSD license.
""""""
from __future__ import annotations
from typing import List
from pipescaler.termini.copy_file_... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 18 10:51:54 2016
@author: hxw186
Factor out regression model of my own implementation.
My own Negative Binomial implementation relies on the statsmodels python library.
This library is not well-implemented. Therefore, my own NB implementation here
is deprecated.
"""
f... |
from fs.opener import open_fs
def test_opener_webdav():
result = open_fs('webdav://foo.bar/webdav')
assert result.url.startswith('http://foo.bar')
def test_opener_webdav_443():
result = open_fs('webdav://foo.bar:443/webdav')
assert result.url.startswith('https://foo.bar')
def test_opener_webdavs():
... |
from django.test import TestCase
from django.contrib.auth.models import User
from django.shortcuts import reverse
from django.utils import timezone
import datetime
import decimal
from .models import Savings
class SavingsViewsTests(TestCase):
def setUp(self):
# Create a user and give them some data to te... |
import urllib.parse
from requests import Response
from py365.auth import AppConnection
from py365.data import BaseData
class BaseResource:
"""
Represent a base resource API on the OG
Every OG API class should inherit from this class
"""
def __init__(self, connection: AppConnection, edgeBase):
... |
import smart_imports
smart_imports.all()
def balance(request):
return {'c': constants,
'f': formulas,
'tt_emissaries_constants': tt_emissaries_constants,
'tt_politic_power_constants': tt_politic_power_constants,
'tt_clans_constants': tt_clans_constants}
|
"""undo set null for user.unix_account_id
Revision ID: 5b6f5a33e426
Revises: 38fa5154b920
Create Date: 2019-10-13 23:03:12.165450
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = '5b6f5a33e426'
down_revision = '38fa5154b920'
branch_labels = None
d... |
#!/usr/bin/env python
import json
def pretty_json(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ':'))
def twitter_small_relation_key():
relation_key = {
"userName" : "chushumo",
"programName" : "multiway_join",
"relationName" : "twitter_small"
}
retur... |
#!/usr/bin/env python
import schemabase
class SchemaUpdate17111(schemabase.SchemaUpdate):
'''
This will add boolean 'advanced' field to leginon.UserData to indicate if a user is an advanced user
'''
def upgradeLeginonDB(self):
if not self.leginon_dbupgrade.columnExists('UserData', 'advanced'):
self.leginon_... |
from rest_framework import serializers
from django.contrib.auth.models import Group
from django.core.exceptions import ValidationError
from core.models import (
User, Asset, SecurityUser, AssetLog,
UserFeedback, CHECKIN, CHECKOUT, AssetStatus, AllocationHistory,
AssetCategory, AssetSubCategory, AssetType, A... |
#!/usr/bin/python3
"""
Implement various sorting algorithms using 'MergeSort_array.txt' and
'QuickSort_array.txt' arrays.
"""
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Set of functions implementing reinforcement algorithms on the maze environment
@author: Nicola Dalla Pozza
"""
import datetime
import json
import math
import pickle
import random
import time
from collections import namedtuple
from itertools import count
import os
im... |
from unittest import TestCase
from microfreshener.core.refiner import KubernetesRefiner
class TestKubernetesRefiner(TestCase):
@classmethod
def setUpClass(self):
self.refiner = KubernetesRefiner('data/tests/refiner/test_load_kingress.yml')
def test_load_kdeployment(self):
docs = self.refi... |
"""
Author: Matt Hanson
Created: 27/01/2021 9:49 AM
"""
import numpy as np
import os
from scipy.stats import pearsonr, truncnorm
import netCDF4 as nc
from copy import deepcopy
import matplotlib.pyplot as plt
from matplotlib.cm import get_cmap
from warnings import warn
import datetime
class MovingBlockBootstrapGene... |
import pandas as pd
import numpy as np
import lightgbm as lgb
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import KFold, RepeatedKFold
from scipy import sparse
# 显示所有列
pd.set_option('display.max_columns', None)
... |
import pandas as pd
import numpy as np
'''
Use this folder for any exploratory
data analysis
'''
|
# Copyright (c) 2020 Horizon Robotics. 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 applicab... |
""" Class for Metallicity PDF
"""
from __future__ import print_function, absolute_import, division, unicode_literals
import warnings
import numpy as np
from scipy.interpolate import interp1d
import pdb
class GenericPDF(object):
"""A Class for any PDF
"""
def __init__(self, x, pdf, parent=None, dx=None... |
import argparse
import copy
import glob
import os
from typing import Tuple
import numpy as np
import pandas as pd
import pycocotools.mask as coco_mask
from tqdm import tqdm
from run_cam_infer import decode_ascii_mask
from src.dataset.utils import ErrorSample, save_segm_label
from src.utils.util import print_argparse_... |
import json
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
with open("packages/reactivated/package.json", "r") as package:
version = json.load(package)["version"]
setuptools.setup(
name="reactivated",
version=version,
author="Silvio Gutierrez",
author_email... |
# pylint: disable=no-self-use,unsubscriptable-object
from selenium.webdriver.common.by import By
import re
import pytest
from . import skip_if_ci, AbstractViewsTests, get_test_default_layers, factory_build_layers
from .selenium.page import IndexPage
@pytest.fixture(scope='function')
@pytest.mark.usefixtures('dbsess... |
#!/usr/bin/env python
import state_mapper
class QuadrantView(state_mapper.StateMapper):
"""
The Quandrant View class maps the snake board as follows:
* The resultant view is RELATIVE to the snake's head.
* It returns a five tuple
+ The first four elements of the pair form a description vec... |
class Balances:
def __init__(self):
self.asset = ''
self.free = 0.0
self.locked = 0.0
@staticmethod
def json_parse(json_data):
result = Balances()
result.asset = json_data.get_string('asset')
result.free = json_data.get_float('free')
resu... |
from PIL import Image
import numpy as np
from multiprocessing import Process, Queue
import time
def main():
width = 1920
hight = 1080
start_x = -2.5
stop_x = 1
start_y = -1.2
stop_y = 1.2
max_iter = 5
thread_count = 4
output_path = "renders/{}.jpg"
for i in range(5,100,5):
... |
import unittest
import src.utilities.manifest.manifest as util
from src.constants.ultrasound import (
FOCUS_HASH_LABEL,
IMAGE_TYPE,
IMAGE_TYPE_LABEL
)
from unittest.mock import MagicMock, ANY
class Test_FrameImageTypeMatch(unittest.TestCase):
def test_image_all_true(self):
frame = {}
... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 3 21:59:22 2020
@author: Aurelius
"""
import glob
from PIL import Image
import itertools
import sys
import subprocess
import time
import argparse
import os
def collager(max_width,padding,folders,output,comp,bg_color):
## Open output image
def openImage(path... |
###########################################################################
#
# Copyright 2020 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
#
# https://www.apache.org/l... |
from streamlink.plugins.mediaklikk import Mediaklikk
from tests.plugins import PluginCanHandleUrl
class TestPluginCanHandleUrlMediaklikk(PluginCanHandleUrl):
__plugin__ = Mediaklikk
should_match = [
'https://www.mediaklikk.hu/duna-world-elo/',
'https://www.mediaklikk.hu/duna-world-radio-elo',... |
import pytest
from django.contrib.auth import get_user_model
from mixer.backend.django import mixer
from ..models import Family, Child
from person_app.models import Birth
from core.models import (
DateTime,
GivName,
SurName,
SURNAME_DICT,
)
pytestmark = pytest.mark.django_db
class TestFamily:
de... |
modelPath="../model/01/01.h5"
testSetPath="../data/mytest"
import keras
from keras.models import load_model
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as pyplot
import numpy as np
import common
import preprocessing
import batch
model = load_model(modelPath)
test_generator = bat... |
import numpy as np
from six.moves import xrange
from keras.layers import Input, Dense, LSTM
from kgp.models import Model
from kgp.layers import GP
from kgp.losses import gen_gp_loss
N = 256
batch_size = 64
input_shape = (32, 10)
lstm_dim = 16
dense_dim = 1
optimizer = 'adam'
gp_test_config = {
'hyp': {'lik': -... |
from django.apps import AppConfig
class KeybaseVerificationConfig(AppConfig):
name = 'keybase_verification'
label = 'keybaseverification'
verbose_name = 'Keybase Verification'
|
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/11_interface.ipynb (unless otherwise specified).
__all__ = ['tqdm_wrapper', 'check_version_and_hardware', 'wrapped_partial', 'create_database', 'import_raw_data',
'feature_finding', 'search_data', 'recalibrate_data', 'score', 'isobaric_labeling', 'protein_grou... |
dataset_type = 'KittiDataset'
data_root = 'data/kitti/'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True, with_bbox3d=True),
dict(type='Resize', img_scale=(1920, 8... |
"""
Reinforcement learning maze example.
This script is our maze environment, in which a bike driver tries to arrive at FINAL POINT.
This script is modified from https://morvanzhou.github.io/tutorials/
"""
import numpy as np
import time
import sys
from random import choice
if sys.version_info.major == 2:
import ... |
def num_translate_adv(value: str) -> str:
"""переводит числительное с английского на русский """
some_dict = {
"zero": 'ноль',
"one": 'один',
"two": 'два',
"three": 'три',
"four": 'четыре',
"five": 'пять',
"six": 'шесть',
"seven": 'семь',
"... |
"""
----------------------------------------------------------------------------------------
Copyright (c) 2020 - see AUTHORS file
This file is part of the ARTHuS software.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU Affero General Public License as published by... |
import project.server.main.parsers as parsers
MAPPING = {
'10.1016': {"func": parsers.parse_elsevier},
'10.1038': {
"func": parsers.parse_springer,
"cbs": [parsers.parse_nature]
},
'10.1007': {
"func": parsers.parse_springer,
"cbs": [parsers.parse_nature]
},
... |
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
setup(
name='duimap',
description='Unix-style du for IMAP',
author='bildzeitung',
author_email='bildzeitung@gmail.com',
url='http://casa.blan.ca',
packages=find_packages(exclude=["tests"]),
test_suite='nose.collec... |
from datetime import datetime
import exifread
from PIL import Image
from PIL.ExifTags import TAGS
def get_timestamp(filename):
ts = PILWrapper.get_timestamp(filename)
if ts is None:
ts = ExifReadWrapper.get_timestamp(filename)
return date_text_to_filename(ts) if ts is not None else Non... |
# pylint: disable=missing-docstring, invalid-name
from django.db import migrations
# pylint: disable=unused-argument
def forwards_test(apps, schema_editor):
pass
# pylint: disable=unused-argument
def backwards_test(apps, schema_editor):
pass
class Migration(migrations.Migration):
operations = [
... |
from django.core.cache import cache
from rest_framework import serializers
from ..constants import (
SESSION_CACHE_KEY, SESSION_CACHE_TIMEOUT, CATEGORY_CACHE_KEY, CATEGORY_CACHE_TIMEOUT, EVENT_CACHE_KEY,
EVENT_CACHE_TIMEOUT
)
from ..models import CategoryEvent, Event, EventSession, Session
class EventSession... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import asyncio
import requests
import functools
import unicodedata
from lxml import html
from Constants import *
emojiTextFile = open(EMOJIS_TXT, 'r')
lines = emojiTextFile.readlines()
EMOJIS = [line[:-1].split(',') for line in lines]
MAX_EMOJI_COUNT... |
import pytest
from etcdb import ProgrammingError
from etcdb.resultset import Column, ColumnSet, Row, ResultSet, ColumnOptions
def test_column():
col = Column('foo')
assert col.name == 'foo'
def test_column_eq():
col1 = Column('foo')
col2 = Column('foo')
assert col1 == col2
def test_column_ne(... |
import database
import optparse
import time
parser = optparse.OptionParser()
parser.add_option("--host", type='string', default='127.0.0.1:10000')
parser.add_option("--user", type='string', default='root')
parser.add_option("--password", type='string', default=None)
parser.add_option("--no-sp", default=False, action='... |
"""
Script for opening GitHub pull request
"""
import argparse
import logging
import os
from typing import Any, Dict
import giturlparse
import operatorcert
from operatorcert import github
LOGGER = logging.getLogger("operator-cert")
def setup_argparser() -> Any:
"""
Setup argument parser
Returns:
... |
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import cv2,time,os
from moviepy.editor import *
from tkinter import filedialog as fd
def im_to_ascii(im:Image,width:int=640,keepAlpha:bool=True,highContrastMode:bool=False,fontResolution:int=5):
ratio:float = width/im.size[0]
... |
# ----------------------------------------------------------------------
# Alcatel.TIMOS.get_interfaces
# ----------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
... |
import visa
class E8254A(object):
def __init__(self,gpibAdress=19,name=None,pow_amp_lim=28):
freqSynthID = "GPIB::"+str(gpibAdress)+"::INSTR"
rm = visa.ResourceManager()
self.name = name
self.inst = rm.open_resource(freqSynthID,read_termination='\n')
self.pow_amp_lim = pow_amp_lim
def query(se... |
# -*- coding: utf-8 -*-
"""ALL. LSTM Autoencoder h480 .ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1v2LQ5tkkHiIkS-GOMdxP_pTmSF6B0Zmt
"""
from google.colab import drive
drive.mount('/content/drive')
data_dir = '/content/drive/My Drive/Colab N... |
'''
@author: HeQingsong
@date: 2019-11-28 17:48
@filename: MacdCylinderDownUp.py
@project: fin_quant
@python version: 3.7 by Anaconda
@description:
todo 增加 ma 或者 macd 辅助选币
'''
from huobi.constant import CandlestickInterval
from mycode.calc.QuotationDF import StockQuotationDF
from mycode.strategy.c... |
import os
import sys
import datetime
import json
import urllib.parse
import logging
from threading import Thread
from requests.utils import requote_uri
from modules.cdGetLowest import getLowestSources
from collections import OrderedDict
class ModuleManager():
"""docstring for ModuleManager"""
def __init__(se... |
from django.test import Client, TestCase
# User class from django
from django.contrib.auth.models import User, UserManager
from django.contrib.auth.hashers import make_password
# from http://www.mechanicalgirl.com/view/testing-django-apps/
class LoginTests(TestCase):
@classmethod
def setUpClass(cls):
... |
"""
Example of an open multi-lane network with human-driven vehicles.
"""
from flow.controllers import IDMController
from flow.core.experiment import SumoExperiment
from flow.core.params import SumoParams, EnvParams, \
NetParams, InitialConfig, InFlows
from flow.core.vehicles import Vehicles
from flow.envs.loop.lo... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from django import forms
from django_summernote.widgets import SummernoteWidget
from .models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['title', 'published', 'comment_allowed', 'summary', 'content', 'author']
widgets = {
'content': S... |
alpha = 'abcdefghijklmnopqrstuvwxyz'
final = ''
input1 = input("Enter a String")
key = int(input("Enter Value of Key"))
input1 = input1.lower()
for x in input1:
if(x in alpha):
pos = alpha.find(x)
pos = (pos+key)%26
final+=(alpha[pos])
else:
final+=x
print(final)
|
# Generated by Django 3.1.6 on 2021-02-23 20:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('complaints', '0003_auto_20210224_0122'),
]
operations = [
migrations.AlterField(
model_name='complaintsinfo',
name='... |
"""
Once a model is learned, use this to drive it.
"""
import numpy as np
from nn import neural_net
import tensorflow as tf
import socket
import smbus
from time import sleep
import json
TCP_HOST = '192.168.42.1'
CAM_HOST = '169.254.251.205'
TCP_PORT = 5005
CAM_PORT = 8000
BUFFER_SIZE = 1024
NUM_SENSORS = 42
# Goal... |
import argparse
import configparser
import smtplib
import ssl
import sys
import time
from wiserHeatingAPI import wiserHub
def get_battery_data(device):
battery_voltage = device.get('BatteryVoltage')
if battery_voltage is not None:
battery_voltage = battery_voltage / 10
else:
battery_voltag... |
import asyncio
class ResponseStreamManager:
def __init__(self):
self.loop = asyncio.new_event_loop()
class ResponseStream:
def __init__(self):
self.callbacks = []
def onData(self, callback):
self.callbacks.append(callback)
async def send(self, data, last = False):
for... |
# Copyright (c) 2019 Microsoft Corporation
# Distributed under the MIT software license
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
from ....test.utils import synthetic_classification, adult_classification
from ....test.utils import synthetic_regression
import numpy as np
from ..ebm impo... |
# ERC20 token with Ownable, Burnable, Mintable, and Transfer Lock features.
# Contributors: Binod Nirvan
# This file is released under Apache 2.0 license.
# Burnable tokens are such tokens that can be irreversibly burned (destroyed).
# Ported from Open Zeppelin
# https://github.com/OpenZeppelin
# https://github.com/eth... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
print(sum([[1, 2], [3, 4], [5, 6]], []))
""")
def test_sum_tuple(self):
se... |
#!/usr/bin/env python
# Trains on image data to learn car steering angles for a simulated track
# November 29, 2017
# Tiffany Huang
import os
import csv
import cv2
import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn.model_selection import train_test_split
from keras.models import Sequential... |
import torch
from torch import nn
from torch.autograd import Variable
from torch import einsum
import torch.nn.functional as F
import numpy as np
from ..distribution.distribution_based import CrossentropyND, TopKLoss, WeightedCrossEntropyLoss
from ..utils import get_tp_fp_fn, get_intersection_union, flatten, sum_tensor... |
import time
from django.http import HttpResponse
from django.shortcuts import render
import os, sys
import json
import LicenseModel.models as LM
import Compliance.licenseExtract as LE
import ClauseAnalysis.LicenseMatcher as LCM
import Compliance.complianceAnalysis as LCA
def upload_file(myfolder):
for file in m... |
import chardet
import os.path
import glob
import sys
import re
def readdir(path, confidence=0.6):
'''path : Specific Directory Path and Filename Extension.
confidence[0.0-1.0] : Specific the detect encode confidence.
File will be ignore if below this value.
'''
title = []
documents = []
unk... |
import os
import fixtures
import testtools
import string
from tcutils.parsers.netperfparse import NetPerfParser
from tcutils.parsers.pingparse import PingParser
from common.connections import ContrailConnections
from testresources import ResourcedTestCase
from config import ConfigPerformance
from tcutils.parsers.flow_... |
"""VisitNepal2020 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/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')
Clas... |
import re
try:
import subprocess32 as subprocess
except ImportError:
import subprocess
import json
import os
from pandaharvester.harvestercore import core_utils
from pandaharvester.harvestercore.work_spec import WorkSpec
from pandaharvester.harvestercore.plugin_base import PluginBase
# logger
baseLogger = co... |
#!/usr/bin/env python3
import math
def fib():
x, y = 0, 1
while True:
yield x
x, y = y, x+y
def even(seq):
for number in seq:
if not number % 2:
yield number
def main(seq):
for number in seq:
if number > 4000000:
break
yield number
print(sum(even(main(fib()))))
# Answer: 4613732
|
from youtube_dl import YoutubeDL
import concurrent.futures
from pytube import Playlist
from config import config
class Downloader:
audio_downloads = []
video_downloads = []
playlist_audio_downloads = []
playlist_video_downloads = []
def __init__(self):
self.audio_ydl_options = {
... |
from typing import Union
from localtileserver.client import TileClient
from localtileserver.tileserver import get_data_path
def get_pine_gulch_url():
return "https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2018-02-16/pine-gulch-fire20/1030010076004E00.tif"
def get_blue_marble(port: Unio... |
# Sequential stuff is all fine and good, but what *if* I want to only do something under a certain condition?
# Well, you can use If-statements. Good ol' ELIFS, we all love them conditionals. y'know how it is.
# In Python, we use the keywords "True" and "False" to declare a boolean expression, like so:
isThisABoole... |
"""
A hierarchy of classes for nonlinear algebraic system solvers.
.. inheritance-diagram:: proteus.NonlinearSolvers
:parts: 1
"""
import numpy
import numpy as np
from math import *
import math #to disambiguate math.log and log
from LinearAlgebraTools import *
from LinearSolvers import *
from .Profiling import *
... |
"""
XXX
============================
"""
import numpy as np
from os import path as op
import matplotlib.pyplot as plt
import mne
from mne.preprocessing import ICA as ICA_mne
from mne.datasets import sample
from picard import picard
from smica import ICA, transfer_to_ica, JDIAG_mne, dipolarity
# raw_fname = os.pat... |
from .base import * # noqa
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = env.bool('APP_DEBUG', True)
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env(... |
from helper import greetings
greetings("hello world") |
from __future__ import print_function
import os
import argparse
DEFAULT_KMER_SIZE = os.environ.get("KMER_SIZE", 21)
DEFAULT_DB_NAME = os.environ.get("DB_NAME", "mykrobe")
DEFAULT_MCCORTEX_31 = "mccortex31"
# os.path.dirname(
# os.path.realpath(__file__))+"/../mccortex/bin/mccortex31"
sequence_or_graph_parser_mixin... |
# Set the account, avatar, rooms, etc. with which the bot will start
def config():
username = "" # [required]
password = "" # [required]
avatarid = "" # [optional] ID for the avatar the bot should attempt to use
init_rooms = [] # [optional] names or aliases for rooms the bot should join
#... |
"""
Copyright 2015 Rackspace
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
dist... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.