text stringlengths 1 927k |
|---|
import os
import requests
import logging
from html.parser import HTMLParser
logger = logging.getLogger(__name__)
EARTHDATA_USER = os.getenv("RF_EARTHDATA_USER")
EARTHDATA_PASS = os.getenv("RF_EARTHDATA_PASS")
def get_stream(session, url, auth, previous_tries):
"""Traverse redirects to get the final url for MOD... |
import json
import subprocess
from pathlib import Path
import pytest
from sanic_routing import __version__ as __routing_version__
from sanic import __version__
def capture(command):
proc = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=Path(__fil... |
"""
Define typing templates
"""
from abc import ABC, abstractmethod
import functools
import sys
import inspect
import os.path
from collections import namedtuple
from collections.abc import Sequence
from types import MethodType, FunctionType
import numba
from numba.core import types, utils
from numba.core.errors impor... |
"""Tests for hello function."""
import pytest
from sequencegenerator.generatePool import generatePool
def test_generatePool():
"""Example test with parametrization."""
my_pool = generatePool(input_sequence='ACACAGTCATCGATCGXXXXXACAGCCXXXXXXGAC',initial_temperature=8, iteration_length=1000, Tm_flexibility=5, ... |
#
# 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 us... |
import time
import threading
try:
from greenlet import getcurrent as get_ident
except ImportError:
try:
from thread import get_ident
except ImportError:
from _thread import get_ident
class CameraEvent(object):
"""An Event-like class that signals all active clients when a new frame is
... |
from dolfin import Cell, UserExpression, Function
import numpy as np
def cell_orientation(is_1d_in_3d):
'''A line mesh in 3d cannot be oriented - fall back to 0'''
return lambda cell: cell.orientation() if not is_1d_in_3d else 0
class DegreeOfFreedom(object):
'''Evaluator of dof of V on functions'''
... |
from bs4 import BeautifulSoup
import requests
URL = "https://www.instagram.com/{}/"
def get_data(a):
data = {}
a = a.split("-")[0]
a = a.split(" ")
data['Followers'] = a[0]
data['Following'] = a[2]
data['Posts'] = a[4]
return data
def scrape_data(username):
b = requests.get(URL.format(username))
a ... |
import sys
def main(inp, out):
string = inp.readline().strip()
a_first = True
answer = []
for char in reversed(string):
if (char == 'a') == a_first:
answer.append('1')
a_first = not a_first
else:
answer.append('0')
print(' '.join(reversed(answer)... |
#!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#----------------------------------------------------------------... |
from rest_framework import serializers # Django Rest Frameworkをインポート
from .models import Product # models.py のcouponクラスをインポート
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product # 扱う対象のモデル名を設定する
fields = '__all__' |
#!/usr/bin/env python
import rospy
import numpy as np
import math
import tf
from std_msgs.msg import String
from geometry_msgs.msg import Twist
from apriltags2_ros.msg import AprilTagDetectionArray
class Tag_listener(object):
def __init__(self):
self._pub_tag0 = rospy.Publisher('/tag0_info', Twist, queue_size=1)
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Brand',
fields=[
('id', models.AutoField(verbos... |
import logging
import ssl
import paho.mqtt.client as mqtt
from roombapy.const import MQTT_ERROR_MESSAGES
MAX_CONNECTION_RETRIES = 3
class RoombaRemoteClient:
address = None
port = None
blid = None
password = None
log = None
was_connected = False
on_connect = None
on_disconnect = Non... |
from typing import Dict
from argparse import Action
def _pair(value):
if isinstance(value, tuple):
if len(value) == 1:
value = value * 2
return value
elif isinstance(value, list):
return tuple(value)
else:
return (value, value)
def merge_pars... |
import os
import re
import sys
import importlib
from aq.cli.commands import AQCommand
class Command(AQCommand):
description = "Displays this help message"
def run(self):
print("\nAzure Query CLI\n")
print("This tool provides an easy to use CLI implementation of the Microsoft Graph API REST ... |
import email
import os.path
import time
from django.conf import settings
from django.test import TestCase
from django_mailbox_abstract import models, utils
from django_mailbox_abstract.models import Mailbox, Message
class EmailIntegrationTimeout(Exception):
pass
def get_email_as_text(name):
with open(
... |
# stdlib
import sqlite3
import time
import pytest
# project
import ddtrace
from ddtrace import Pin
from ddtrace.constants import ANALYTICS_SAMPLE_RATE_KEY
from ddtrace.contrib.sqlite3 import connection_factory
from ddtrace.contrib.sqlite3.patch import patch, unpatch, TracedSQLiteCursor
from ddtrace.ext import errors
... |
#coding:utf-8
#
# id: bugs.core_1150
# title: Error conversion error from string " " using outer join on int64 and int fields
# decription:
# tracker_id: CORE-1150
# min_versions: []
# versions: 2.1
# qmid: bugs.core_1150
import pytest
from firebird.qa import db_factory, isql_act, Act... |
# -*- coding: utf-8 -*-
import os
import qiniu
from qiniu import Auth
from gevent import monkey
from gevent.pool import Pool
from config import config
monkey.patch_socket()
def down(token, key, localfile, mime_type, delete=False):
ret, info = qiniu.put_file(
token, key, localfile,
... |
#! /usr/bin/env python3
# Written by Martin v. Löwis <loewis@informatik.hu-berlin.de>
"""Generate binary message catalog from textual translation description.
This program converts a textual Uniforum-style message catalog (.po file) into
a binary GNU catalog (.mo file). This is essentially the same function as the
G... |
# 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 ... |
"""
TESTS:
We test various degenerate cases of kernel computation:
sage: matrix(ZZ,1,0).kernel()
Free module of degree 1 and rank 1 over Integer Ring
Echelon basis matrix:
[1]
sage: matrix(QQ,1,0).kernel()
Vector space of degree 1 and dimension 1 over Rational Field
Basis matrix:
[1]
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
通过class 实例化对象可以直接修改内部属性的特性
再通过魔法方法,赋予实例化对象 具有内部属性_redis_client的方法和属性
主要参考 flask-redis扩展实现
https://github.com/underyx/flask-redis/blob/master/flask_redis/client.py
redis 连接
"""
import sys
from aioredis import create_redis_pool, Redis
from redis import Redis, Authenti... |
class Article:
'''
Class that instantiates objects of the news article objects of the news sources
'''
def __init__(self,author,description,time,url,image,title):
self.author = author
self.description = description
self.time = time
self.url = url
self.image = imag... |
"""
#Trains a ResNet on the CIFAR10 dataset.
"""
from __future__ import print_function
import keras
from keras.layers import Dense, Conv2D, BatchNormalization, Activation
from keras.layers import AveragePooling2D, Input, Flatten
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, LearningRa... |
"""
This module contains the core classes of version 2.0 of SAX for Python.
This file provides only default classes with absolutely minimum
functionality, from which drivers and applications can be subclassed.
Many of these classes are empty and are included only as documentation
of the interfaces.
$Id: saxlib.py,v 1... |
# Copyright 2019 The TensorFlow Authors. 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 applica... |
import torch
from .builder import CUDAOpBuilder
class QuantizerBuilder(CUDAOpBuilder):
BUILD_VAR = "DS_BUILD_QUANTIZER"
NAME = "quantizer"
def __init__(self, name=None):
name = self.NAME if name is None else name
super().__init__(name=name)
def absolute_name(self):
return f'd... |
import streamlit as st
from detect import detector
import cv2
import numpy as np
import time
import math
import imutils
import warnings
warnings.filterwarnings('ignore')
menu = ['Welcome', 'Social distancing detector', 'Learn more!']
with st.sidebar.beta_expander("Menu", expanded=False):
option = st.selectbox('C... |
from .Lexer import Lexer
from .Pattern import Pattern
from .Token import Token
from .TokenList import TokenList |
#!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a bitcoind or Bit... |
from hashids import Hashids
import time
def proccess_payment_simulation(payment_method, card_hash):
time.sleep(60)
hashids = Hashids(alphabet='abcdefghijklmnopqrstuvwxyz1234567890', min_length=22)
return hashids.encode(1) |
"""
Django settings for demo_api project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# ... |
"""
Rhino Python Script Tutorial
Advanced
Exercise 00
Analytical surfaces - the roof of the British Museum.
Bibliography:
Williams, Christopher JK. "The analytic and numerical definition of the geometry of the British Museum Great Court Roof." (2001): 434-440.
"""
import rhinoscriptsyntax as rs
import math
nx ... |
#!/usr/bin/env python3
"""
Usage: poetry run test_parser FR production
"""
import datetime
import logging
import pprint
import time
import arrow
import click
from parsers.lib.parsers import PARSER_KEY_TO_DICT
from parsers.lib.quality import (
ValidationError,
validate_consumption,
validate_exchange,
... |
# Copyright 2015 The TensorFlow Authors. 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 applica... |
#!/usr/bin/env python
"""
Output functions for logical operator machine products
"""
import numpy as np
from numba import jit, prange # int8, float64,
# fuzzy output functions mapping from scalar vectors of probabilities to
# to single data-point
# OR-AND
@jit('float64(float64[:], float64[:])', nogil=True, nopytho... |
from django.conf.urls import url
from . import views
from django.contrib import auth
app_name = 'blog'
urlpatterns = [
url(r'^$',views.PostList.as_view(),name='post_list'),
url(r'^about/$',views.AboutView.as_view(),name='about'),
url(r'^post_detail/(?P<pk>\d+)$',views.PostDetail.as_view(),name='post_detai... |
# Copyright 2018-2020 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fil... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# phial documentation build configuration file, created by
# sphinx-quickstart on Sat Jul 1 21:23:47 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# auto... |
# 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... |
import asyncio
import json
import logging
_LOGGER = logging.getLogger(__name__)
class SomfyMyLink:
"""Wraps access to a Somfy MyLink Hub via the Somfy Synergy API."""
def __init__(self, system_id, host, port=44100):
self.system_id = system_id
self.host = host
self.port = port
... |
from Models.PAE_models.Encoder_CNN import EncoderCNN
from Models.PAE_models.Decoder_CNN import DecoderCNN
from Models.PAE_models.Bijecter import RealNVP
from sklearn.preprocessing import MinMaxScaler
from Models.AE_CNN_interface import AE_CNN
import joblib
class PAECNN(AE_CNN):
def __init__(self, filters, dim, s... |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
# Copyright (C) 2007-2012 Red Hat
# see file 'COPYING' for use and warranty information
#
# policygentool is a tool for the initial generation of SELinux policy
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the ... |
"""
Django settings for social_net project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
... |
from tkinter import *
from time import sleep, time
from random import randint
from math import sqrt
MAGASSÁG = 500
SZÉLESSÉG = 800
ablak = Tk()
ablak.title('Buborékpukkasztó')
v = Canvas(ablak, width=SZÉLESSÉG, height=MAGASSÁG, bg='darkblue')
v.pack()
hajó_1 = v.create_polygon(7, 2, 7, 28, 30, 15, fill='red')
hajó_2 = ... |
#!/usr/bin/python3
# encoding: utf-8
""" run_web_pycode 's entry_points"""
import fire
from run_web_pycode.core import read_proxy, run_remote_script, set_proxy
def entry_point() -> None: # pragma: no cover
"""
默认函数 触发fire包
https://github.com/google/python-fire
"""
fire.core.Display = lambda line... |
from __future__ import division, absolute_import, print_function
import os
import re
import sys
import imp
import copy
import glob
import atexit
import tempfile
import subprocess
import shutil
import distutils
from distutils.errors import DistutilsError
try:
set
except NameError:
from sets import Set as set
... |
#!/usr/bin/env python
# Copyright (c) 2019 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
import glob
import os
import sys
from CarDetector import CarDetector
from Dri... |
import argparse
from approch import Model
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--niter', type=int, default=20, help='number of epochs per task')
parser.add_argument('--lr', type=float, default=1e-4, help='learning rate')
parser.add_argument('--beta', type=float, def... |
import sys
import json
infile = open(sys.argv[1],'r')
if len(sys.argv) > 2:
outfile = open(sys.argv[2],'w')
else:
outfile = sys.stdout
js = json.load(infile)
for x in js['results']:
outfile.write(x['url']+'\n')
infile.close()
outfile.close() |
"""Module contains classes used by the Nginx Configurator."""
import re
from certbot.plugins import common
ADD_HEADER_DIRECTIVE = 'add_header'
class Addr(common.Addr):
r"""Represents an Nginx address, i.e. what comes after the 'listen'
directive.
According to the `documentation`_, this may be address[:p... |
def run():
from django.conf import settings
from django.test.utils import get_runner
runner = get_runner(settings)()
return runner.run_tests(('mailviews',))
def __main__():
import logging
import sys
logging.basicConfig(level=logging.DEBUG)
sys.exit(run())
if __name__ == '__main__'... |
"""Forward facing fitz tools with information about ecosystem."""
import os
import re
import sys
import imp
import os.path as op
import numpy as np
import subprocess
from nipype import config, logging
from .tools import make_subject_source
def gather_project_info():
"""Import project information based on environm... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 1 19:35:08 2018
@author: fnord
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
################################################################################# MCC
#k = [0.8593737651, 0.8553389745, 0.7784318972, 0.9113220823, 0.8003214083, ... |
from plyer import notification
import time
if __name__ == "__main__":
while True:
notification.notify(
title = "DRINK WATER", # Title of the Notification
message = "Hey friend, It's time to drink water", # Message of the Notification
app_icon = 'Drink-Water-Notificati... |
import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Era_Phase2C9_cff import Phase2C9
process = cms.Process("PROD",Phase2C9)
process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi")
process.load("IOMC.EventVertexGenerators.VtxSmearedGauss_cfi")
process.load("Configuration.Geometry.GeometryExtended2026D49_c... |
def load_config(config_data):
if 'infinispan' not in config_data:
raise Exception("infinispan section is mandatory in the configuration")
required_keys_1 = ('endpoint', 'username', 'password')
if not set(required_keys_1) <= set(config_data['infinispan']):
raise Exception('You must provide ... |
from pettingzoo import AECEnv
from pettingzoo.utils.agent_selector import agent_selector
from gym import spaces
import rlcard
import random
from rlcard.games.uno.card import UnoCard
import numpy as np
from pettingzoo.utils import wrappers
from .rlcard_base import RLCardBase
def env(**kwargs):
env = raw_env(**kwar... |
# coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
im... |
#!/usr/bin/env python3
"""
This script is used for course notes.
Author: Erick Marin
Date: 12/19/2020
"""
def to_seconds(hours, minutes, seconds):
return hours*3600+minutes*60+seconds
print("Welcome to this time converter")
cont = "y"
while(cont.lower() == "y"):
hours = int(input("Enter the number of hou... |
"""
* Pantsu need some serious work
Regular data single_torrent parser not working from other Nyaa alternatives
Needs some work
"""
print("TODO") |
import autopath
import sys
from pypy import conftest
class AppTestBuiltinApp:
def setup_class(cls):
class X(object):
def __eq__(self, other):
raise OverflowError
def __hash__(self):
return 42
d = {X(): 5}
try:
d[X()]
... |
# Copyright (c) 2015. Mount Sinai School of Medicine
#
# 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 o... |
notice = """
Flip XY or 90 degree rotation demo
-----------------------------------
| Copyright 2022 by Joel C. Alcarez |
| [joelalcarez1975@gmail.com] |
|-----------------------------------|
| We make absolutely no warranty |
| of any kind, expressed or implied |
|-----------------------------------|
| T... |
import contextlib
from datetime import datetime, timezone
import getpass
import io
import json
import pathlib
import uuid
import pickle
import hashlib
import subprocess
from os.path import join, exists
import numpy as np
import sqlalchemy as sqla
from sqlalchemy.ext.declarative import declarative_base as sqla_declarat... |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Legendgrouptitle(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "surface"
_path_str = "surface.legendgrouptitle"
_valid_props = {"font", "text"}
... |
# Copyright 2019 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... |
# coding: utf-8
"""
GMO Aozora Net Bank Open API
OpenAPI spec version: 1.1.12
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from ganb_corporate_client.a... |
""" This is meant to show user how to use the API"""
import os
from flasgger import Swagger
from app import app
swagger = Swagger(app)
@app.route('/api/v1/auth/signup/', methods=["POST"])
def signup():
""" endpoint for registering users.
---
parameters:
- name: name
required: true
... |
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name, unused-import, missing-docstring, exec-used
# pylint: disable=unused-argument, too-few-public-methods, redefined-builtin
# pylint: disable=no-name-in-module, no-member, undefined-variable
# pylint: disable=import-error
# flake8: noqa
"""
pygments_markdown_lexe... |
import argparse
import logging
import yaml
import re
from federatedscope.core.auxiliaries.utils import logfile_2_wandb_dict
parser = argparse.ArgumentParser(description='FederatedScope result parsing')
parser.add_argument('--exp_dir',
help='path of exp results',
required=True,
... |
"""
Speakerdeck Tag
---------------
This implements a Liquid-style speakerdeck tag for Pelican.
Syntax
------
{% speakerdeck id %}
Example
-------
{% speakerdeck 82b209c0f181013106da6eb14261a8ef %}
Output
------
<script async class="speakerdeck-embed" data-id="82b209c0f181013106da6eb14261a8ef"
data-ratio="1.3333333... |
#!/usr/bin/env python
import asyncio
import os
import schedule
import sys
import time
import uvloop
os.environ['MODE'] = 'PRO'
sys.path.append('../../')
from owllook.fetcher.cache import update_all_books
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.get_event_loop()
def update_all_books_sc... |
#!/usr/bin/env python3
"""Combine logs from multiple bitcoin nodes as well as the test_framework log.
This streams the combined log output to stdout. Use combine_logs.py > outputfile
to write to an outputfile.
If no argument is provided, the most recent test directory will be used."""
import argparse
from collection... |
# Copyright (c) 2021 PaddlePaddle Authors. 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... |
# Generated by Django 3.2.9 on 2021-11-06 14:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_auto_20211106_1750'),
]
operations = [
migrations.AddField(
model_name='post',
name='stablish_date',
... |
from bson import ObjectId
from openpyxl import Workbook
from .person_model import PersonModel
from application.utils.exception.custom_exception import CustomException
class LaunchedFormsModel:
def __init__(self, current_app, open_id):
self.__current_app = current_app
self.__person = PersonModel(... |
import seaborn as sns
import matplotlib.pyplot as plt
from datos import data
import pandas as pd
sns.set(style="white")
f, ax = plt.subplots(figsize=(6, 15))
d=data('mtcars')
subset1, subset2, subset3= d[d.cyl==4], d[d.cyl==6], d[d.cyl==8]
datos=pd.DataFrame ({'Max': [max(subset1.mpg), max(subset2.mpg), max(subset3.mp... |
"""Test cltk.lemmatize."""
import os
import unittest
from unittest.mock import patch
from cltk.data.fetch import FetchCorpus
from cltk.lemmatize.backoff import (
DefaultLemmatizer,
DictLemmatizer,
IdentityLemmatizer,
RegexpLemmatizer,
UnigramLemmatizer,
)
from cltk.lemmatize.grc import GreekBackoff... |
from __future__ import print_function
import wave
import matplotlib.pyplot as plt
import matplotlib.style as ms
import numpy as np
import scipy.io as io
import pyAudioAnalysis
from pyAudioAnalysis import audioBasicIO
from pyAudioAnalysis import audioFeatureExtraction
import datetime
import sys
import os
docPath = 'C:... |
'''
Copyright (c) 2008 Georgios Giannoudovardis, <vardis.g@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy,... |
import Cookie
import os
from django.conf import settings
from common.tests import ViewTestCase
from common import api
from common import clean
from common import util
class JoinTest(ViewTestCase):
def setUp(self):
super(JoinTest, self).setUp()
self.form_data = {'nick': 'johndoe',
'fi... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import pytest
@pytest.mark.online
class TestWhatCDOnline(object):
config = """
tasks:
badlogin:
whatcd:
username: invalid
... |
"""
The Parsing module implements the following exception classes:
* Exception
* SpecError
* UnexpectedToken
"""
# ============================================================================
# Begin exceptions.
#
class AnyException(Exception):
"""
Top-level class for all exceptions thrown within the P... |
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from abc import abstractmethod
from enum import Enum
from pants.build_graph.mirrored_target_option_mixin import MirroredTargetOptionMixin
from pants.engine.platform import Platform
from p... |
import datetime
import rjm
from pathlib import Path
def cmd_journal(project_code, model_path, jrn_path, com_dir, log_dir):
command_path = Path(__file__).parent
command_name = command_path.name
time_stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
rvt_jrn = rjm.JournalMaker()
com_data = {
... |
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
saved = [
"din0",
"din1",
"din2",
"din3",
"sel0",
"sel1",
"sel_b0",
"sel_b1",
"dout",
]
def read_data(f):
data = defaultdict(lambda: [])
for line in f.readlines():
values = line.... |
import numpy as np
import fast.fast9 as fast9
import mahatos as mh
from scipy import ndimage
import scipy.stats
import warnings
from skimage import img_as_float, img_as_int
from skimage.color import rgb2gray
from skimage import io
from skimage.feature import local_binary_pattern, corner_harris
from skimage.feature impo... |
# -*- coding: utf-8 -*-
"""
Python API
==========
Provides functions for communicating with `orion.core`.
"""
import logging
import orion.core.io.experiment_builder as experiment_builder
from orion.client.cli import (
interrupt_trial,
report_bad_trial,
report_objective,
report_results,
)
from orion.c... |
import numpy as np
from keras_bert import load_trained_model_from_checkpoint
import os
from dataloader import Tokeniser, load_data
from sklearn.model_selection import train_test_split
from keras.layers import *
from keras.optimizers import Adam
from keras.models import Model
from keras.callbacks import EarlyStopping,... |
import unittest # Importing the unittest module
from Userlogin import User # Importing the contact class
class TestUser(unittest.TestCase):
'''
Test class that defines test cases for the user class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
'''
... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
def run_publisher():
pub1 = rospy.Publisher('/terrapin/velocity', String, queue_size=10)
pub2 = rospy.Publisher('/terrapin/messages', String, queue_size=10)
pub3 = rospy.Publisher('/terrapin/misc', String, queue_size=10)
rate ... |
from __future__ import absolute_import
import six
from base64 import b64encode
from django.core.urlresolvers import reverse
from django.core import mail
from mock import patch
from exam import fixture
from pprint import pprint
from sentry.constants import RESERVED_ORGANIZATION_SLUGS
from sentry.models import (
A... |
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
import numpy as np
# import tensorflow as tf
from PIL import Image
import os
import matplotlib.pyplot as plt
import pickle
# %%
def load_images(path: str) -> list:
'''
Load images from a directory. Normalize the image to... |
# Copyright 2020 The Forte Authors. 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 applicable ... |
# SPDX-License-Identifier: Apache-2.0
#
# http://nexb.com and https://github.com/nexB/scancode.io
# The ScanCode.io software is licensed under the Apache License version 2.0.
# Data generated with ScanCode.io is provided as-is without warranties.
# ScanCode is a trademark of nexB Inc.
#
# You may not use this software ... |
def prime(interval):
primes = []
for number in range(2,interval):
flag = True
for x in range(2,number):
if x<number:
if number%x != 0:
x+=1
else:
flag = False
else:
break
if flag:
primes.append(number)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.