content stringlengths 5 1.05M |
|---|
# coding=utf-8
from phi.tf.flow import *
from .pde.pde_base import collect_placeholders_channels
from .sequences import StaggeredSequence, SkipSequence, LinearSequence
from .hierarchy import PDEExecutor
class ControlTraining(LearningApp):
def __init__(self, n, pde, datapath, val_range, train_range,
... |
import torch.nn as nn
import torch
import os
import torch.nn.functional as F
import torchvision.models as models
from torch.autograd import Variable
import torchvision.utils as vutils
import torchvision.transforms as transforms
import numpy as np
from util.metrics import PSNR
from skimage.measure import compare_ssim as... |
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
import time
import numpy as np
from torch.autograd import Variable
from PIL import Image
import os, random
from collections import OrderedDict
f... |
#!/usr/bin/env python3
# references:
# rfc1928(socks5): https://www.ietf.org/rfc/rfc1928.txt
# asyncio-socks5 https://github.com/RobberPhex/asyncio-socks5
# handshake
# +----+----------+----------+
# |VER | NMETHODS | METHODS |
# +----+----------+----------+
# | 1 | 1 | 1 to 255 |
# +----+----------+----------... |
#!/usr/bin/python
# Check interface utilization using nicstat
# nicstat needs to be in $PATH
# Author: Mattias Mikkola
import subprocess
import sys
from optparse import OptionParser
from numpy import mean
parser = OptionParser()
parser.add_option('-i', '--interface', dest='interface', help='Interface to monitor')
pars... |
# Generated by Django 3.0.8 on 2020-08-14 13:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0010_auto_20200814_1212'),
]
operations = [
migrations.AddField(
model_name='contact',
name='sap_id',
... |
from distutils.core import setup, Command
from distutils.dir_util import copy_tree
import sys
import os
import pyvx.nodes
import pyvx.capi
from pyvx import __version__
mydir = os.path.dirname(os.path.abspath(__file__))
class InstallLibCommand(Command):
user_options = []
def initialize_options(self):
... |
import warnings
import time
from skmultiflow.visualization.base_listener import BaseListener
from matplotlib.rcsetup import cycler
import matplotlib.pyplot as plt
from matplotlib import get_backend
from skmultiflow.utils import FastBuffer, constants
class EvaluationVisualizer(BaseListener):
""" This class is resp... |
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import pyplot
from sklearn.linear_model import LinearRegression
from sklearn import ensemble
from sklearn.cross_validation import train_test_split
#%%
def DataRead(str1, useCols, tablenames):
dataTable = pd.read_csv("%s" % ... |
import codecs
import os
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='ampr',
version='1.0.0',
description='Amateur Packet Radio API client',
long_d... |
from django.conf.urls import url
from django.conf.urls.static import static
from django.urls import path, include, re_path
from provarme_tenant.views import (TenantRegisterView, Login, Logout, activate, TenantProfile, PendingPageView, ThankPageView, create_purchase_upnid)
from provarme import settings
app_name="prova... |
import feedparser
import models
import time
import datetime as dt
from bs4 import BeautifulSoup
VALID_IMAGE_ATTRIBUTES = ('alt', 'title', 'src')
def fetch(url):
f = feedparser.parse(url)
feed = models.Feed()
feed.link = url
feed.website = f.feed.get('link')
feed.title = f.feed.get('title')
f... |
#!/usr/bin/python
"""
Plot parameter 1D marginal constraints as a fn. of FG subtraction efficiency.
"""
import numpy as np
import pylab as P
from rfwrapper import rf
nsurveys = 2 #5
nbins = 14
name = ['SD', 'Interferom.']
#name = ['A', 'B', 'C', 'D', 'E']
cols = ['b', 'g', 'c', 'r', 'y']
P.subplot(111)
for j in rang... |
# import unittest
# from main import randomly_distribute
# class TestRandomlyDistribute(unittest.TestCase):
# def test_random_distribute(self):
# tokens = 10
# for i in range(10):
# groups = 5 + i
# result = randomly_distribute(tokens, groups)
# self.assertEqual(... |
import numpy as np
import cv2
import argparse
import sys
import time
from calibration_store import load_stereo_coefficients
def depth_map(imgL, imgR):
""" Depth map calculation. Works with SGBM and WLS. Need rectified images, returns depth map ( left to right disparity ) """
# SGBM Parameters -----------------... |
def for_FIVE():
"""printing numbr 'FIVE' using for loop"""
for row in range(5):
for col in range(4):
if col==0 and row!=3 or col==3 and row!=1 or row==0 or row==2 or row==4:
print("*",end=" ")
else:
print(" ",end=" ")
print()
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Written by Lucas Sinclair and Paul Rougieux.
JRC biomass Project.
Unit D1 Bioeconomy.
"""
# Third party modules #
# First party modules #
# Internal modules #
from cbmcfs3_runner.graphs.inventory import InventoryAtStart, InventoryAtEnd
from cbmcfs3_runner.graphs... |
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from badges.utils import MetaBadge
from studio.helpers.mixins import BadgeMixin
from ..figures.models import Model3D
class ModelBadgeMixin:
model = Model3D
def get_user(self, instance):
return instance.designer
... |
from flask import Blueprint
bp = Blueprint('routes', __name__)
from . import index_view, auth_user, cuentas_views, librodiario_view
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Created by techno at 27/05/19
#Feature: #Enter feature name here
# Enter feature description here
#Scenario: # Enter scenario name here
# Enter steps here
import numpy as np
my_array = np.array([1,2,3,4])
my_2d_array = np.array([[1, 2, 3, 4],
[5, 6, 7, 8]])
... |
from bype import Bype
class MyServer(object):
def __init__(self, host, port=9090):
self.host = host
self.port = port
self.isrunning = False
def start(self):
self.isrunning = True
print 'server started at %s:%d' % (self.host, self.port)
def _handle... |
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/api/')
def index():
return "Hello World"
if __name__ == '__main__':
app.run(debug=True) |
from output.models.ms_data.regex.re_i10_xsd.re_i10 import (
Regex,
Doc,
)
__all__ = [
"Regex",
"Doc",
]
|
import os, sys
os.chdir("G:\\My Drive\\Academic\\Research\\Neural Heap")
import tensorflow as tf
class TFGraphUtils(object):
def _init__(
self):
pass
def set_args(
self,
config):
self.config = config
def initialize_weights_cpu(
... |
"""
Subsample from CS6 GT only those images that are used in the Dets or HP JSON.
srun --mem 10000 python tools/face/mod_json_gt_det.py
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
sys.path.app... |
#!/usr/bin/python
#given a smarts rxn file (backwards), a core scaffold smarts file (with name containing connecting atoms)
# an sdf file with the results of clustering scaffolds and an input sdf file and an
#output prefix, output the extracted reactant conformations aligned to their scaffold
import sys,gzip,argparse... |
"""
You're given a string s consisting solely of "(" and ")". Return whether the parentheses are balanced.
Constraints
n ≤ 100,000 where n is the length of s.
https://binarysearch.com/problems/Balanced-Brackets
"""
from collections import deque
class Solution:
def solve(self, s):
left = 0
for c i... |
# Adam Shaat
# program that outputs whether it is a weekday
# or a weekend
import datetime
now = datetime.datetime.now()
day = now.weekday()
weekend = (5,6)
dayname ={0:'Monday', 1:'Tuesday', 2:'Wednesday', 3:'Thursday', 4:'Friday', 5:'Saturday', 6:'Sunday'}
# assigning to print the weekday
print(dayname[day])
if ... |
r"""
Contains two classes used for sweep functionalities.
NOTE : Both of these classes are not intended to be directly instanciated by the user.
:class:`Simulation <quanguru.classes.Simulation.Simulation>` objects **has** ``Sweep/s`` as their attributes, and
``_sweep/s`` are intended to be created by ca... |
# -*- coding: utf-8 -*-
# Pytest test suite
import pytest
from result import Result, Ok, Err
@pytest.mark.parametrize('instance', [
Ok(1),
Result.Ok(1),
])
def test_ok_factories(instance):
assert instance._value == 1
assert instance.is_ok() is True
@pytest.mark.parametrize('instance', [
Err(2)... |
# Write a function day_name that converts an integer number 0 to 6 into the name of a day.
# Assume day 0 is “Sunday”.
# Once again, return None if the arguments to the function are not valid. Here are some tests that should pass:
# test(day_name(3) == "Wednesday")
# test(day_name(6) == "Saturday")
# test(day_name(42) ... |
import sys
import random
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication
from rx import Observable
from rx.subjects import Subject
from rx.concurrency import QtScheduler
from client.client_window import ClientWindow
REFRESH_STOCK_INTERVAL = 100
def random_stock(x):
symbol_names = [
['... |
import matplotlib.pyplot as plt
import pandas as pd
def print_data(csv_1, csv_2, ax, title):
# Uses the first column for the x axes.
csv_1.plot(x=csv_1.columns[0], marker='o', xticks=[32,256,512], ax=ax)
csv_2.plot(x=csv_2.columns[0], marker='x', xticks=[32,256,512], ax=ax)
# Set the title.
ax.set... |
# Use by adding e.g. "command script import ~/uno/scripts/unolldb.py" to ~/.lldbinit
import lldb
from sets import Set
moduleName = __name__
logFile = '/tmp/' + moduleName + '.log'
unoPrimitiveTypes = {
"Uno.Long": "int64_t",
"Uno.Int": "int32_t",
"Uno.Short": "int16_t",
"Uno.SByte": "i... |
from securityheaders.models.xcontenttypeoptions import XContentTypeOptions
from securityheaders.checkers import Checker
class XContentTypeOptionsChecker(Checker):
def __init__(self):
pass
def getxcontenttypeoptions(self, headers):
return self.extractheader(headers, XContentTypeOptions)
|
# source: https://github.com/kuangliu/pytorch-cifar/blob/master/models/densenet.py
'''DenseNet in PyTorch.'''
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from cnns.nnlib.pytorch_layers.conv_picker import Conv
def conv3x3(in_planes, out_planes, args, stride=1):
"""3x3 convoluti... |
from datetime import datetime
import errno
import fcntl
import os
import socket
import sys
import traceback
import threading
import xml.etree.ElementTree as ET
from zmq.eventloop import ioloop
from tornado import iostream
from pyfire import configuration as config
from pyfire.errors import XMPPProtocolError
from pyfi... |
#
# PySNMP MIB module CISCOSB-RMON (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-RMON
# Produced by pysmi-0.3.4 at Mon Apr 29 18:07:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... |
"""
@Author : Ailitonia
@Date : 2021/07/17 2:04
@FileName : config.py
@Project : nonebot2_miya
@Description :
@GitHub : https://github.com/Ailitonia
@Software : PyCharm
"""
from pydantic import BaseSettings
class Config(BaseSettings):
# 是否启用正则匹配matcher
# 如果 ... |
# Generated by Django 2.1.2 on 2018-11-02 15:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("data_refinery_common", "0005_auto_20181030_1955"),
]
operations = [
migrations.AddField(
model_name="surveyjob",
nam... |
"""Sleight of Hand ported from https://twitter.com/MunroHoberman/status/1345134382810619913
"""
from pypico8 import (
Table,
add,
circ,
cos,
delete,
pico8_to_python,
print,
printh,
rectfill,
rnd,
run,
sin,
t,
)
printh(
pico8_to_python(
"""
d={}r,e=rectfi... |
# coding: utf-8
# flake8: noqa
"""
Account API
The <b>Account API</b> gives sellers the ability to configure their eBay seller accounts, including the seller's policies (seller-defined custom policies and eBay business policies), opt in and out of eBay seller programs, configure sales tax tables, and get acco... |
from multiprocessing import Pool
from collections import defaultdict
import gym
from el_agent import ELAgent
from frozen_lake_util import show_q_value
class CompareAgent(ELAgent):
def __init__(self, q_learning=True, epsilon=0.33):
self.q_learning = q_learning
super().__init__(epsilon)
def le... |
import socket
from smtplib import *
from configuration import *
debug = False
verbose = True
version = "1.0.0"
key_sender = 'sender'
key_subject = 'subject'
key_username = 'username'
key_password = 'password'
key_receivers = 'receivers'
key_smtp_server = 'smtp_server'
key_smtp_server_port = 'smtp_server_port'
param_... |
# Objective: check whether win conditions can be achieved in one step
def check_horizontale(grille, x, y):
"""Alignements horizontaux"""
symbole = grille.grid[y][x]
# Alignement horizontal de trois jetons consécutifs, le noeud (x,y) étant le plus à droite
if grille.is_far_from_left(x):
if all(... |
user='[email protected]'
password='secretsecret'
base_url = 'http://cdn.mydomain.net'
platform = 'production'
lambda_region = 'us-east-1'
sourcebucket = 'mybucket'
# not used yet
sdb_region = 'us-east-1'
sdb_domain = 'purge-akamai'
sdb_item='bucket-map' |
# -*- coding: utf-8 -*-
from marshmallow import ValidationError
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPBadRequest
from amnesia.modules.content.validation import IdListSchema
from amnesia.modules.content import SessionResource
def includeme(config):
''' Pyramid includeme '''... |
graph = [
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, "cat", 0, 1, 0, 0, 0],
[0, 1, 0, 1, 0, "bone", 0],
[0, 0, 0, 0, 0, 0, 0]
]
class Node:
# 表示从cat方块到当前方框的距离
G = 0
# 当前方块到目标点(我们把它称为点B,代表骨头!)的移... |
from __future__ import unicode_literals
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
|
from random import random
import theme_utils
import input_utils
def pick_theme(themes):
sum_of_ratings = sum([theme['rating'] for theme in themes])
random_number = random() * sum_of_ratings
chosen_theme_number = 0
while themes[chosen_theme_number]['rating'] < random_number:
random_number -= t... |
import os
import sys
from setuptools import setup, find_packages
if sys.version_info[0] < 3:
with open('README.rst') as f:
long_description = f.read()
else:
with open('README.rst', encoding='utf-8') as f:
long_description = f.read()
setup(
name='piotr',
version='1.0.2',
description... |
# Copyright (c) 2016, Intel Corporation.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU General Public License,
# version 2, as published by the Free Software Foundation.
#
# This program is distributed in the hope it will be useful, but WITHOUT
#... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
from .experiment import Datapoint
def _build_columns_list(datapoints: tp.List[Datapoint]) -> tp.List[str]:
columns: ... |
"""
bing.py
Copyright 2006 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope that it wil... |
# --- coding: utf-8 ---
import sqlite3
from ipaddress import ip_address, ip_network
from settings import snmp_user, snmp_password
from pprint import pprint
from pysnmp.entity.rfc3413.oneliner import cmdgen, mibvar
from pysnmp.proto.rfc1902 import OctetString
from check import check_ip
import paramiko
from pprint impor... |
from .openapi import (
JSONResponse,
Parameter,
ParameterIn,
register_operation,
RequestBody,
Response,
setup,
)
__all__ = (
"JSONResponse",
"Parameter",
"ParameterIn",
"register_operation",
"RequestBody",
"Response",
"setup",
)
|
import re
import os
class DevelopmentConfigs:
_sds_pool_base = os.path.join(os.getcwd(), 'dev/sds_pool')
_test_base = os.path.join(os.getcwd(), 'dev/test')
SDS_PDF_FILES = os.path.join(_sds_pool_base, 'sds_pdf_files')
SDS_TEXT_FILES = os.path.join(_sds_pool_base, 'sds_text_files')
TEST_SDS_PDF_F... |
"""
Created on Aug 20, 2020
@author: joseph-hellerstein
Codes that provide various analyses of residuals.
There are 3 types of timeseries: observed, fitted, and residuals
(observed - fitted).
Plots are organized by the timeseries and the characteristic analyzed. These
characteristics are: (a) over time,... |
import numpy as np
def create_vocabulary(input_text):
flat = ' '.join(input_text)
vocabulary = list(set(flat))
vocab_size = len(vocabulary)
char_to_idx = {char: idx for idx, char in enumerate(vocabulary)}
idx_to_char = {idx: char for idx, char in enumerate(vocabulary)}
return {'vocab_size': vo... |
def load(h):
return ({'abbr': '2tplm10',
'code': 1,
'title': '2m temperature probability less than -10 C %'},
{'abbr': '2tplm5',
'code': 2,
'title': '2m temperature probability less than -5 C %'},
{'abbr': '2tpl0',
'code': 3,
... |
#!/usr/bin/env python
# -*- coding: ISO-8859-1 -*-
# generated by wxGlade 0.4 on Sun Mar 26 01:48:08 2006
import wx
class mainFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: mainFrame.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds... |
import json
from pathlib import Path
from typing import Tuple, Union
from openff.recharge.aromaticity import AromaticityModels
from openff.recharge.charges.bcc import (
BCCCollection,
BCCParameter,
original_am1bcc_corrections,
)
from openff.recharge.charges.library import LibraryChargeCollection
from openf... |
# Copyright 2020 Richard Jiang, Prashant Singh, Fredrik Wrede and Andreas Hellander
#
# 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 r... |
__version__="1.0.2"
|
# vFabric Administration Server API
# Copyright (c) 2012 VMware, Inc. 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
... |
# -*- coding: utf-8 -*-
"""Writer for travis.yml files."""
from __future__ import unicode_literals
import os
from l2tdevtools.dependency_writers import interface
class TravisYMLWriter(interface.DependencyFileWriter):
"""Travis.yml file writer."""
_TEMPLATE_DIRECTORY = os.path.join('data', 'templates', '.travi... |
# -*- coding: utf-8 -*-
import codecs
import nltk
from nltk.tokenize import sent_tokenize
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk import pos_tag
from nltk.stem import WordNetLemmatizer
from nltk.stem import PorterStemmer
from nltk.corpus import treebank
#mytext = ""... |
import logging
import time
from useful.resource.readers import ResourceURL, readers
from useful.resource.parsers import parsers
_log = logging.getLogger(__name__)
def cached_load(timeout=300):
"""
Define timeout to be used in `load()` function.
Args:
timeout (int, optional): Number of seconds t... |
# coding: utf-8
"""
Workflow Execution Service
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
im... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: tfutils.py
# Author: Qian Ge <[email protected]>
import tensorflow as tf
def sample_normal_single(mean, stddev, name=None):
return tf.random_normal(
# shape=mean.get_shape(),
shape=tf.shape(mean),
mean=mean,
stddev=stddev,
dtype=tf.float32,... |
import sys
from importlib import reload
from django.urls import clear_url_caches
import pytest
pytestmark = pytest.mark.django_db
DOCS_URL = "/docs/"
@pytest.fixture
def all_urlconfs():
return [
"apps.core.urls",
"apps.users.urls",
"conf.urls", # The ROOT_URLCONF must be last!
]
... |
# -*- coding: utf-8 -*-
"""Align the Prefix Commons with the Bioregistry."""
from typing import Any, Dict, Mapping, Sequence
from bioregistry.align.utils import Aligner
from bioregistry.external.prefix_commons import get_prefix_commons
__all__ = [
"PrefixCommonsAligner",
]
class PrefixCommonsAligner(Aligner):... |
# 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
# d... |
import json
import time
from fidesops.core.config import load_toml
from fidesops.models.connectionconfig import (
AccessLevel,
ConnectionConfig,
ConnectionType,
)
from fidesops.models.datasetconfig import DatasetConfig
import pytest
import pydash
import os
from typing import Any, Dict, Generator
from tests... |
#!/usr/bin/python3
# coding : utf-8
def letter_position(letter):
# Lowercase
if letter >= 97 and letter <= 122:
return letter - 97
# Uppercase
elif letter >= 65 and letter <= 90:
return letter - 65
else:
return 0
def letter_case(letter):
# Lowercase
... |
import os
from datetime import datetime
from course_lib.Base.Evaluation.Evaluator import EvaluatorHoldout
from scripts.model_selection.cross_validate_utils import write_results_on_file, get_seed_list
from scripts.scripts_utils import read_split_load_data
from src.data_management.data_reader import get_ICM_train_new, g... |
# Test akara.dist.setup()
import sys
import os
import tempfile
import subprocess
import shutil
from akara import dist
class SetupException(Exception):
pass
# Do a bit of extra work since nosetests might run in the top-level
# Akara directory or in test/ .
dirname = os.path.dirname(__file__)
setup_scripts_dir = o... |
from sklearn.model_selection import GridSearchCV
class HypoSearcher(object):
def __init__(self, clf):
self.clf = clf
def optimize(self, x, y, params):
clf_search = GridSearchCV(self.clf, params, verbose=100).fit(x, y)
clf = clf_search.best_estimator_
return clf
|
"""
This file is part of the L3Morpho package.
L3Morpho is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
L3Morpho is dis... |
import gdb
class Register :
"""
Helper to access register bitfield
>>> reg = Register(0x80000000000812d0)
>>> hex(reg.get_bitfield(60, 4))
'0x8'
>>> hex(reg.get_bitfield(0, 44))
'0x812d0'
>>> reg.set_bitfield(60, 4, 9)
>>> hex(reg.value)
'0x90000000000812d0'
>>> reg.set_bit... |
import sys
with open(sys.argv[1], "r") as a_file:
for line in a_file:
print(line.strip()
.replace(u'\u00AD', ' ')) |
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(label='Select a file')
def clean_file(self):
docfile = self.cleaned_data['docfile']
ext = docfile.name.split('.')[-1].lower()
if ext not in ["pdf"]:
raise forms.ValidationError("Only pdf and... |
# Generated by Django 2.1.7 on 2019-03-11 02:00
import django.utils.datetime_safe
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("db_data", "0012_auto_20190210_1637")]
operations = [
migrations.AddField(
model_name="officer",
... |
"""Package signing."""
import pickle
from django_q import core_signing as signing
from django_q.conf import Conf
BadSignature = signing.BadSignature
class SignedPackage:
"""Wraps Django's signing module with custom Pickle serializer."""
@staticmethod
def dumps(obj, compressed: bool = Conf.COMPRESSED) -... |
#!/usr/bin/env python
import subprocess
import os
import datetime
import settings
import logging
import ssl
import sqlite3
import psutil
import requests
import json
import paho.mqtt.client as paho
from prom_lib import prometheus as prom
class speedbot():
def __init__(self):
#connect to the mqtt broker
... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! Inc. 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.or... |
from dataclasses import field
from typing import Optional
from pydantic.dataclasses import dataclass
@dataclass
class Book:
title: str
price: int
quantity: Optional[int] = 0
_price: int = field(init=False, repr=False)
@property
def total(self):
return self.price * self.quantity
@... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__a... |
import time
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdriver.common.by import By
from ensconce.dao import resources, groups
from tests.functional import SeleniumTestController
class R... |
import torch
import numpy as np
import os
import pandas as pd
import SimpleITK as sitk
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm
class NiftyDatasetFromTSV(Dataset):
"""Creates a PyTorch Dataset using a .tsv file of .nii.gz paths and labels."""
def __init__(self, tsv_file, age_lim... |
def calculate_investment_value(initial_value, percentage, years):
result = initial_value * (1 + percentage / 100) ** years
return result
|
from requests import get, exceptions
from re import compile, match, MULTILINE
from sys import exit
# url = "https://raw.githubusercontent.com/fire1ce/DDNS-Cloudflare-PowerShell/main/README.md"
# section_name = "License"
# section_name = "License"
url = "https://raw.githubusercontent.com/wsargent/docker-cheat-sheet/m... |
#
# PySNMP MIB module ELTEX-ARP-INTERFACE-TABLE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-ARP-INTERFACE-TABLE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:45:32 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ve... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=C0103
# pylint: disable=E1101
# Python 2/3 compatibility
from __future__ import print_function
import glob
import os
import math
import numpy as np
def getCenterAndWH(name):
lines = open(name, "rt").readlines()
centerAndWH = [int(line) for line in l... |
import collections
#ChainMap提供了一种方便的方法,用于创建一个新实例,
# 在maps列表的前面有一个额外的映射,
# 以便于避免修改现有的底层数据结构。
a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}
m1 = collections.ChainMap(a, b)
m2 = m1.new_child()
print('m1 before:', m1)
print('m2 before:', m2)
m2['c'] = 'E'
print('m1 after:', m1)
print('m2 after:', m2)
"""
m1 before... |
#!/usr/bin/env python
import roslib
import rospy
import math
from std_msgs.msg import Float64
from random import random
def main():
rospy.init_node("cos")
pub = rospy.Publisher("/cos", Float64, queue_size=1)
counter = 0
RESOLUTION = 100
while not rospy.is_shutdown():
if counter == RESOLUTIO... |
from datetime import date, timedelta
from decouple import config
from itsdangerous import (TimedJSONWebSignatureSerializer
as Serializer, BadSignature, SignatureExpired)
from passlib.apps import custom_app_context as pwd_context
from api.app import db
class User(db.Model):
__tablename__ ... |
import numpy as np
import argparse
import osgeo.gdal as gdal
from scipy.spatial import voronoi_plot_2d, Voronoi
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull, convex_hull_plot_2d
from numpy import genfromtxt
import pandas as pd
import gdal
import os
import xarray as xr... |
import json
from datetime import datetime as dt
import d4rl
import gym
import numpy as np
import torch
from oraaclib.agent import BCQ, BEAR
from oraaclib.environment import get_env
from oraaclib.util.logger import Logger
from oraaclib.util.rollout import oraac_rollout
from oraaclib.util.utilities import get_dict_hyper... |
import io
import os
import json
import subprocess
import shutil
import boto3
from .storage import Storage
class S3Storage(Storage):
def __init__(self, bucket: str, key: str, local_path: str):
super().__init__()
self.bucket = bucket
self.key = key
self.index_key = key+"/index"
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.