content stringlengths 5 1.05M |
|---|
import numpy as np
import matplotlib.pyplot as plt
class walker:
def __init__(self, x, y, model, p0, psig=None, cost=None):
self.x = np.array(x)
self.y = np.array(y)
self.model = model
#Define a cost function.
if cost == None:
self.cost = lambda p, x=x, y=y, m=m... |
"""
Testing python dependency graph for ancient DNA pipeline
@author James Boocock
@date 18 Feb 2016
"""
import pytest
from ngadnap.dependency_graph.graph import CommandNode, CommandGraph, Graph
from ngadnap.dependency_graph.job_queue import JobQueue
import os
class TestCommandGraph:
def te... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# ======================================================================================================================== #
# Project : Natural Language Recommendation #
# Version : 0.1.0 ... |
import qnt.data as qndata
import time
idx_list = qndata.load_index_list()
print(idx_list)
idx_data = qndata.load_index_data(forward_order=False)
print(idx_data)
|
"More on Cygwin Python for Windows"
'''
os.fork call is present in the Cygwin version of Python on Windows.
Even though this call is missing in the standard version of Python for Windows, you
can fork processes on Windows with Python if you install and use Cygwin.
the Cygwin fork call is not as efficient and does no... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Ed Mountjoy, Jeremy Schwartzentruber
#
import sys
import os
import json
import pandas as pd
import yaml
import pprint
def main():
# Args
out_manifest = 'configs/manifest.json'
in_studies = pd.read_csv('configs/tabix_ftp_paths.tsv', sep='\t')
in_complet... |
# Copyright (c) 2019, IRIS-HEP
# 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 conditions and the foll... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# URL generator. Inherit and override this for derivative classes (e.g. 420chan API, 8chan/vichan API)
class Url(object):
# default value for board in case user wants to query board list
def __init__(self, board, https=False):
self._board = board
s... |
import hou
import os
# from PySide2 import QtGui, QtWidgets, QtCore
import pipe.gui.quick_dialogs as qd
import pipe.gui.select_from_list as sfl
from pipe.tools.houtools.utils.utils import *
from pipe.tools.houtools.importer.importer import Importer
from pipe.am.project import Project
from pipe.am.body import Body
fro... |
# ==========================================================================
#
# Copyright NumFOCUS
#
# 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... |
# flake8: noqa
import os
from datetime import datetime
from pathlib import Path
from subprocess import CalledProcessError
from ...common.git import Commit
from ..constants import SkinStyle
PROJECT_NAME = "bmds-server"
BASE_DIR = Path(__file__).parents[2].resolve()
ROOT_DIR = Path(__file__).parents[3].resolve()
# da... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 26 12:26:23 2021
@author: Viktor Semenov
"""
from scrapper import scrape_link
from producer import file_check
import schedule
import time
txt_dir = ('TXTfiles')
link=input('Please enter the URL for scrapping: ')
scrape_link(link)
schedule.ever... |
# -*- coding: utf-8 -*-
import logging
from typing import List, AnyStr
import psycopg2
from psycopg2 import DatabaseError, IntegrityError, errorcodes
from psycopg2.extensions import AsIs
from psycopg2.extras import DictCursor, DictRow
from buoy.client.device.common.item import BaseItem
logger = logging.getLogger(__... |
import os
from micro_records import celery
@celery.task
def walk_directory(root, extensions=['.mp3']):
pass
|
import hikari
from src.github_handler import GithubHandler
from src.utils import get_channel_list, get_mentions_from, get_pr_embed, get_issue_embed
class Anigitrest(hikari.RESTApp):
def __init__(self, *args, **kwargs):
if 'github_token' not in kwargs:
raise Exception('Missing github token'... |
import os
import h5py
import numpy as np
import multiprocessing as mp
import tkinter as tk
from tkinter import filedialog
from ipywidgets import interact
import ipywidgets as widgets
from tqdm.notebook import tqdm
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
try:
import b... |
import yaml
class BentoctlException(Exception):
"""
Base class for all of bentoctl's exceptions.
Each custom exception is derived from this base class.
"""
def show(self):
"""
used by CLI to generate a user readable error message.
"""
print(f"Error [{type(self).__n... |
import sys
from shiftscheduler.excel import input as excel_input
from shiftscheduler.excel import output as excel_output
from shiftscheduler.solver import input as solver_input
from shiftscheduler.solver import output as solver_output
from shiftscheduler.validation import validator
_INPUT_FILE_PATH = 'shiftscheduler... |
#A*
#-------------------------------------------------------------------
#B* This file contains source code for the PyMOL computer program C*
#copyright 1998-2000 by Warren Lyford Delano of DeLano Scientific. D*
#-------------------------------------------------------------------
#E* It is unlawful to modify or remove... |
# -*- coding: utf-8 -*-
# Copyright 2013 Takeshi KOMIYA
#
# 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... |
from datetime import datetime
import pytz
from django.test import TestCase
from freezegun import freeze_time
from robber import expect
from data.factories import AttachmentFileFactory
from sitemap.sitemaps.attachment_sitemap import AttachmentSitemap
from sitemap.sitemaps.base_sitemap import BaseSitemap
class Attach... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class TextClassifier(nn.ModuleList):
def __init__(self, params):
super(TextClassifier, self).__init__()
# Parameters regarding text preprocessing
self.seq_len = params.seq_len
self.num_words = params.num_words
self.embedding_si... |
from .base import *
class OpStash(object):
cache = {}
@classmethod
def Add(cls, object):
t = object.type
cls.cache[t] = object
@classmethod
def Lookup(cls, type):
return cls.cache[type]
@classmethod
def Define(cls, pt):
cls.Add(pt)
return pt
class ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from libs.models.samplers.samper import Sampler
from libs.utils.rbbox_overlaps import rbbx_overlaps
from libs.utils import bbox_transform
from libs.utils.coordinate_convert import coordinate... |
#!/usr/bin/python
import socket
import sys
print sys.argv[1],"=====>",socket.gethostbyname(sys.argv[1])
|
"""Tests for pylab tools module.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2011, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#---------... |
t1, t2, n = map(int, input().split())
d = {1: t1, 2: t2}
def fib(n):
if n in d:
return d[n]
else:
a = fib(n - 1) ** 2 + fib(n - 2)
d[n] = a
return a
print(fib(n))
|
def asdjf ( l,
a):
3
+4
|
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Ingredient, Recipe
from recipe.serializers import IngredientSerializer
INGREDIENTS_URL = reverse('recipe:i... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""Tests for signed-binary DB functionality."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from grr_response_server import db
from grr_response_server.rdfvalues import objects as rdf_objects
_test_id1 =... |
"""
eBook Reader Dictionaries
Usage:
wikidict LOCALE
wikidict LOCALE --download
wikidict LOCALE --parse
wikidict LOCALE --render
wikidict LOCALE --convert
wikidict LOCALE --find-templates
wikidict LOCALE --check-random-words N
wikidict LOCALE --check-word=WORD
wikidict LOCALE --get-... |
import sail
from sail import add_docstring
def add_docstring_fcn(class_, method, descr):
cls = getattr(sail.optimizers, class_)
add_docstring(getattr(cls, method), descr)
def add_docstring_class(class_, descr):
add_docstring(getattr(sail.optimizers, class_), descr)
add_docstring_class("Optimizer", r"""... |
import sys
s = sys.stdin.readline().rstrip()
def main():
l = len(s)
t = s[:-1] if l & 1 else s
l = len(t)
while True:
t = t[:-2]
l -= 2
if t[: l // 2] * 2 == t:
return l
if __name__ == "__main__":
ans = main()
print(ans)
|
import pandas as pd
import random
import numpy as np
from Program.classifier.variables import NATIONALITIES
class VectorProcessing:
def __init__(self, wordCountColumn =-2, xStartColumn =0, xEndColumn=-2, pathColumn=-1):
self.wordCountColumn = wordCountColumn
self.xStartColumn=xStartColumn
... |
# -*- coding: utf-8 -*-
"""
Simple waveform recorder with f0 detection.
"""
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
from src.microphone import MicrophoneRecorder
from src.pitch_tracking import time_domain_f0_autocorrelation, frequency_domain_f0_cepstrum
CHUNKSIZE = 2048
SAMPLE... |
#!/usr/bin/env python
"""
Generate MANIFEST.in file.
"""
import os
import subprocess
IGNORED_EXTS = []
IGNORED_FILES = ['.travis.yml', 'appveyor.yml']
IGNORED_PREFIXES = ["files/"]
def sh(cmd):
return subprocess.check_output(
cmd, shell=True, universal_newlines=True).strip()
def main():
files = ... |
import time
def emagFullPage(soup):
data = []
for link in soup.find_all('div', attrs={'class': 'card-section-wrapper'}):
try:
nume = str(
link.contents[1].contents[1].contents[0].contents[1]
.contents[0].get('alt'))
pret = int(
li... |
from django.db import models
from django.conf import settings
from .validators import upload_file_path, upload_file_validator
User = settings.AUTH_USER_MODEL
# Create your models here.
class Uploader(models.Model):
title = models.CharField(max_length=500)
file_code = models.CharField(max_length=11000)
fil... |
"""Console script for esbmc_launcher."""
import sys
import click
from soot_wrapper import SootWrapper
from esbmc import EsbmcLauncher
import printable
from download import download
import utils
def check_soot():
printable.verbose("Checking requirements")
SootWrapper.check_requirements()
def download_depende... |
import os
from pathlib import Path
import torch
from torch.utils.data import Dataset
import cv2
import numpy as np
import pandas as pd
import scipy.io
from .data_utils import generate_rbbox, resize_image, generate_rbbox_v2
# TODO: Training masks and ignore bboxes having ### for training
class ICDARDataset(Dataset)... |
from copy import deepcopy
from great_expectations.render.exceptions import InvalidRenderedContentError
class RenderedContent:
def to_json_dict(self):
return {}
def __eq__(self, other):
if not isinstance(other, self.__class__):
# Delegate comparison to the other instance's __eq__.... |
import curio
import pytest
from async_rx import Observer, Subscription, rx_amb, rx_create, rx_from, rx_range
from async_rx.protocol import default_subscription
from ..model import ObserverCounterCollector
from .model import countdown
def test_rx_amb_init():
with pytest.raises(RuntimeError):
rx_amb()
@... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Libndp(AutotoolsPackage):
"""Libndp - Library for Neighbor Discovery Protocol"""
home... |
from ..factory import Type
class chatActionCancel(Type):
pass
|
import numpy as np
from dc2g.planners.DC2GPlanner import DC2GPlanner
class DC2GRescalePlanner(DC2GPlanner):
def __init__(self, model_name, traversable_colors, goal_color, room_or_object_goal, camera_fov, camera_range_x, camera_range_y, env_to_coor, env_next_coords, env_to_grid, env_grid_resolution, env_render, ou... |
""" Librairie personnelle pour manipulation du dataframe,
description des variables, renommage des colonnes...
"""
#! /usr/bin/env python3
# coding: utf-8
# ====================================================================
# Outils dataframe - projet 3 Openclassrooms
# Version : 0.0.1 - CRE LR 13/03/2021
# Ve... |
#!/usr/bin/env python2.7
#coding=utf-8
#
#The MIT License (MIT)
#
#Copyright (c) 2012-2013 HUB Systems, Inc.
#
#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 with... |
#!/usr/bin/env python3
"""
Index the ESA Worldcover data automatically.
"""
import concurrent.futures
import logging
import sys
from math import ceil, floor
from typing import Tuple
import click
import pystac
import rasterio
from datacube import Datacube
from datacube.index.hl import Doc2Dataset
from datacube.utils im... |
##################################################################
######################## include.py ############################
##################################################################
##### ekate - Enhanced KRATOS for Advanced Tunnel Enineering #####
##### copyright by CIMNE, Barcelona, Spain ... |
import sys
dp = [0]*251
def solve(i):
if i == 0:
return 1
if i == 1:
return 1
elif i == 2:
return 3
if dp[i]:
return dp[i]
dp[i] = solve(i-2) * 2 + solve(i-1)
return dp[i]
for i in sys.stdin:
n = int(i.strip())
print(solve(n))
|
"""
pyart.correct.dealias
=====================
Front end to the University of Washington 4DD code for Doppler dealiasing.
.. autosummary::
:toctree: generated/
dealias_fourdd
find_time_in_interp_sonde
_create_rsl_volume
"""
# Nothing from this module is imported to pyart.correct if RSL is not
# ins... |
from . import _client
from .response_types import (
Albums,
AlbumTracks,
Artists,
ArtistSearch,
RecommendedTracks,
Tracks,
TrackSearch,
)
def combine_chunks(f):
"""
Combine function calls on chunks instead of whole array in one time
:return: All results of the chunks
"""
... |
# -*- coding: utf-8 -*-
"""
Created by huxiaoman 2017.12.12
vgg_tf.py:训练tensorflow版的vgg16网络,对cifar-10shuju进行分类
"""
from datetime import datetime
import math
import time
import tensorflow as tf
import cifar10
batch_size = 16
num_batches = 100
# 定义函数对卷积层进行初始化
# input_op : 输入数据
# name : 该卷积层的名字,用tf.name_scope()来命名
# kh... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
from torch import Size
from neuralcompression.layers import SynthesisTransformation2D
class TestSynthesisTransformation2D:
... |
from django.shortcuts import render,redirect
from django.contrib.auth import(
authenticate,
get_user_model,
login,
logout,
)
from IWP_PROJECT import settings
from .forms import UserLoginForm
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
def login_view(request):
... |
import random
number_of_guests = int(
input("Enter the number of friends joining (including you):\n"))
if number_of_guests < 1:
print("No one is joining for the party")
else:
print(
"\nEnter the name of every friend (including you), each on a new line:")
guests = {}
for _ in range(number_... |
import os
import pytest
from pyls import uris
from pyls.plugins.rope_rename import pyls_rename
from pyls.workspace import Document
DOC_NAME = "test1.py"
DOC = """class Test1():
pass
class Test2(Test1):
pass
"""
@pytest.fixture
def tmp_workspace(workspace):
def create_file(name, content):
fn = o... |
#!/usr/bin/env python3
import sys
import os
import platform
from subprocess import check_output
from subprocess import CalledProcessError
# This script is adapted from https://github.com/mvendra/building/blob/master/build.py
class Builder():
def __init__(_self, basepath, options):
_self.basepath = bas... |
#!/usr/bin/python3
# Setting a default value for a parameter..
def abc(xyz=123):
print(xyz)
abc()
abc(456)
# Output..
#
# 123
# 456
|
from typing import Tuple
from ...cli.cli import cli
from ...cli.common import set_build_config, set_docker_repository_config, run_task, add_options, \
set_job_id
from ...cli.options.build_options import build_options
from ...cli.options.docker_repository_options import docker_repository_options
from ...cli.options... |
#importando tkinter
from tkinter import *
from tkinter import ttk
#cor
cor1 = "#0a0a0a" #preta
cor2 = "#feffff" #branca
cor3 = "#223e6b" #Azul carregado
cor4 = "#8a8380" #Cinza
cor5 = "#f2743a" #laranja
#janela base
janela = Tk()
janela.title("Calculadora")
janela.geometry("235x310")
janela.config(bg=cor1)
#fr... |
import pkg_resources
from pipgrip.pipper import parse_req
class Package(object):
"""Represent a project's package."""
def __init__(self, pip_string): # type: (str) -> None
if pip_string == "_root_":
req = parse_req(".")
req.key = "_root_"
else:
req = pars... |
begin_unit
comment|'# Copyright 2010 United States Government as represented by the'
nl|'\n'
comment|'# Administrator of the National Aeronautics and Space Administration.'
nl|'\n'
comment|'# All Rights Reserved.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); ... |
import json
import glob
import base64
from labelme import utils
from PIL import Image
import copy
from io import BytesIO
dir_images = "../images/type_1/"
file_base = "frame_2021-02-12_194659_IN4.json"
base = dir_images + file_base
with open(base, "r") as f:
data = json.load(f)
def _check_image_height_and_width(i... |
from Module import AbstractModule
class Module(AbstractModule):
def __init__(self):
AbstractModule.__init__(self)
def run(
self, network, antecedents, out_attributes, user_options, num_cores,
out_path):
import os
from genomicode import filelib
from genomicode im... |
from django.db import models
from django.contrib.auth.models import User
class Tweet(models.Model):
title = models.CharField(max_length=255)
content = models.TextField(max_length=280)
created = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.PROTECT)
def ... |
import pytest
from .context import advent_of_code_2019
from advent_of_code_2019.day01 import *
def test_fuel():
assert fuel_required(12) == 2
assert fuel_required(14) == 2
assert fuel_required(1969) == 654
assert fuel_required(100756) == 33583
assert fuel_required2(14) == 2
assert fuel_requir... |
from data_mapper.properties.property import Property
class ListProperty(Property):
def eval_not_none(self, value, **context):
return list(super().eval_not_none(value, **context))
|
from utils import SupplyResult, clean_after_module
from utils.tech import get_dev_channel
subreddit = 'all'
t_channel = get_dev_channel()
def send_post(submission, r2t):
total_size = clean_after_module()
r2t.send_text('Deleted: ' + str(round(total_size / (1024.0 ** 3), 3)) + 'GB.')
return SupplyResult.S... |
"""Package for creation of Presentation State instances."""
from highdicom.pr.sop import (
AdvancedBlendingPresentationState,
ColorSoftcopyPresentationState,
GrayscaleSoftcopyPresentationState,
PseudoColorSoftcopyPresentationState,
)
from highdicom.pr.enum import (
AnnotationUnitsValues,
Blendi... |
import argparse
import csv
import sqlite3
import sys
import random
import time
import sys
import math
def update_member_sql(table):
s='''UPDATE {} SET member=? WHERE callsign LIKE ?'''.format(table)
return s
s='''SELECT * FROM tv WHERE callsign LIKE ?'''
def update_tv_sql():
s='''UPDATE tv SET lictype=?,... |
#!/usr/bin/env python
import json
import os
import cgi
from room import parse_room
args = cgi.FieldStorage()
r_id = args['r_id'].value
# Return JSON object of requested room
path = os.path.join('..', 'config', 'room')
os.chdir(path)
room = parse_room(r_id + '.xml')
print "Content-type: application/json"
print
prin... |
import importlib
from .. import client
def is_online():
"""
Being able to call this function means the server is online and able to handle requests.
:return: True
"""
return True
def echo_message(message):
print(message)
return "I printed: %s" % message
def run_python_script(script_pat... |
from playlist_generator import *
from ngrams import *
|
from seleniumbase import BaseCase
class MultipleDriversTest(BaseCase):
def test_multiple_drivers(self):
self.open("data:text/html,<h1>Driver 1</h1>")
driver2 = self.get_new_driver()
self.open("data:text/html,<h1>Driver 2</h1>")
self.switch_to_default_driver() # Driver 1
... |
import typing
def py_sorted(numbers: typing.List[int]) -> typing.List[int]:
"""The Python sorted algorithm.
Args:
numbers (typing.List[int]): A list of integers.
Returns:
typing.List[int]: A list of integers ordered from smallest value
to largest value.
"""
return sorted(... |
from prodtest import ProduceTestCase
class PretendUpToDate2Test(ProduceTestCase):
def test_pretend_up_to_date_2(self):
# S
# / \
# T V
# /
# U
normal = lambda: self.produce('S')
pretending = lambda: self.produce('S', **{'-u': 'T'})
self.a... |
from ops.data import OpsClass, OpsField, DszObject, DszCommandObject, cmd_definitions
import dsz
import datetime
class TimeData(DszObject, ):
def __init__(self, dszpath='', cmdid=None, opsclass=None, parent=None, debug=False):
DszObject.__init__(self, dszpath, cmdid, (opsclass if opsclass else ds... |
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired, ValidationError
from app.models import Self_Affirmation
def affirmation_exists(form, field):
description = field.data
not_unique = Self_Affirmation.query.filter(
Self_Affirmation.description... |
# encoding = utf-8
__author__ = "Ang Li"
class A:pass
a = A()
# print(bool(A)) # 缺省类的布尔值是True
# print(bool(a)) # 缺省实例的布尔值是True
# 更改实例的布尔值
class B:
# def __bool__(self): # 布尔魔术方法,对实例生效
# return False # bool(B()) = False
def __len__(self): # 没有布尔方法,但是有len方法,则以 len方法的返回结果为准
... |
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render
from ..customModels.model_customer import Customer
from ..customModels.models import CustomUser
from ..customModels.model_inventory import InventoryModel
from ..customModels... |
from pipelines import pipeline
nlp=pipeline("e2e-qg")
ques = nlp("Python is a programming language. Created by Zino and first released in 1991")
print(ques) |
from django.conf import settings
from django.core.mail import get_connection
from django.core.mail.backends.base import BaseEmailBackend
from django_q.tasks import async
EMAIL_BACKEND = getattr(
settings, 'DJANGO_Q_EMAIL_BACKEND',
'django.core.mail.backends.smtp.EmailBackend')
class DjangoQBackend(BaseEmai... |
# -*- coding: utf-8 -*-
# Simple Bot (SimpBot)
# Copyright 2016-2017, Ismael Lugo (kwargs)
import logging
from simpbot.bottools import irc as irctools
from simpbot import localedata
requerimentls = {}
logging = logging.getLogger('simpbot')
failed = True
i18n = localedata.get()
def get(requeriment):
"""get('adm... |
# coding=UTF-8
"""
Tests the representation of UDF files in backup files.
"""
import os.path
import lib
COMMENTS = lib.identifier_variations(100, False)
def put_udf_files(context, comments):
"""
Creates UDF files with the given comments.
"""
for comment in comments:
content = u"--[=======[\n" + comment + u"\... |
'''OpenGL extension EXT.gpu_shader5
This module customises the behaviour of the
OpenGL.raw.GLES2.EXT.gpu_shader5 to provide a more
Python-friendly API
Overview (from the spec)
This extension provides a set of new features to the OpenGL ES Shading
Language and related APIs to support capabilities of new GPUs, ex... |
# -*- coding: utf-8 -*-
import copy
import json
import logging
import time
import uuid
from foglamp.common import logger
from foglamp.plugins.common import utils
from foglamp.services.south import exceptions
from foglamp.plugins.south.apt_eclipse.dnp3_master import Dnp3_Master
""" Plugin for reading data from a B100 ... |
# -*- coding: utf-8 -*-
"""Constants and helpers for python-orcid library."""
from lxml.etree import XML
WORK_NAME2 = u'WY51MF0OCMU37MVGMUX1M92G6FR1IQUW0'
WORK_NAME3 = u'BN237DFI2GF69DFH4Y60FK2J48DF0SKJ5'
exemplary_work = {
"title": {
"title": {
"value": WORK_NAME2
},
},
"... |
"""Helper methods for tests of custom Gym environments.
This is used in our test suite in `tests/test_envs.py`. It is also used in sister
projects such as `imitation`, and may be useful in other codebases.
"""
import re
from typing import (
Any,
Callable,
Iterable,
Iterator,
List,
Mapping,
... |
"""
Code stolen from https://github.com/Rapptz/discord.py
"""
import functools
import discord
from discord.ext import commands
from . import sql
class NotAModError(commands.CheckFailure):
pass
class NoTokenError(Exception):
pass
def is_mod():
async def predicate(ctx):
ch = ctx.channel
... |
from django.http import HttpResponse
from django.template import loader
def base_template(request):
context = {}
return HttpResponse(loader.get_template("base.html").render(context, request))
|
from django.shortcuts import render
from rest_framework import generics
from .models import Appointment
from ..api.serializers import AppointmentSerializer
# Create your views here.
class CreateView(generics.ListCreateAPIView):
queryset = Appointment.objects.all()
serializer_class = AppointmentSerializer
... |
import pyqtgraph as pg
from PyQt5.QtWidgets import *
from scipy.interpolate import interpolate
from GUI.tabs.propulsion_tab.propeller_tab import propeller_tab
from Utils.data_objects.lifting_surface_placeholder import *
from Utils.data_objects.propulsion_keys import *
class propeller_pane(QWidget):
def __init__(... |
import unittest
from functools import partial
import yaml
from dpath.util import get as get_value
from mock import patch, Mock
from kuberender.render import render, run
from kuberender.utils import load_yaml_file
class KubeRenderTestCase(unittest.TestCase):
def _pipe_mock(self, returncode=0):
pipe = Mo... |
import sys
from pretsa_star import Pretsa_star
import pandas as pd
import pickle
import time
filePath = sys.argv[1]
k = sys.argv[2]
t = sys.argv[3]
sys.setrecursionlimit(3000)
targetFilePath = filePath.replace(".csv","_t%s_k%s_pretsa_star.csv" % (t,k))
eventLog = pd.read_csv(filePath, delimiter=";")
start = time.time... |
import os
import numpy as np
from scipy import stats
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.lines import Line2D
from sklearn.manifold import TSNE
matplotlib.use("Agg")
os.chdir(open("../data_dir").read().strip())
sns.set(font_scale=1.3, style='ticks')
fig, axes = plt.s... |
"""
Parser for log files using regular expressions.
.. module:: logparser
:platform: Unix, Windows
:synopis: Parser for log files using regular expressions.
.. moduleauthor:: Thomas Lehmann <thomas.lehmann.private@googlemail.com>
=======
License
=======
Copyright (c) 2017 Thomas Lehmann
Permi... |
"""The Noise attack
"""
import warnings
import numpy as np
import tensorflow as tf
from cleverhans.attacks.attack import Attack
class Noise(Attack):
"""
A weak attack that just picks a random point in the attacker's action space.
When combined with an attack bundling function, this can be used to implement
... |
from statsmodels.tsa.arima_model import ARIMA
def MF_AR_arcov(y,p = 2):
try:
model = ARIMA(y, order=(p,0,0))
model_fit = model.fit( disp=False)
except:
#Non-stationary returns expception
return
ar_coefs = model_fit.arparams
coef_errors = model_fit.bse
outDict = ... |
from units.umath import sqrt, pi
#########
#
# Captures intuitions about orbits without focusing on properties that require time or orientation.
#
# Many equations are derived from http://www.bogan.ca/orbits/kepler/orbteqtn.html and Wikipedia.
#
#########
class TimelessPlanarOrbit:
def __init__( self, r_periapsis,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.