content stringlengths 5 1.05M |
|---|
"""
rbac changes for jupyterhub 2.0
Revision ID: 833da8570507
Revises: 4dc2d5a8c53c
Create Date: 2021-02-17 15:03:04.360368
"""
# revision identifiers, used by Alembic.
revision = '833da8570507'
down_revision = '4dc2d5a8c53c'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
from... |
"""
Parse a Canadian Census XML document (in SDMX format) and yield a CSV with the
same data. The data will be Tidy (http://vita.had.co.nz/papers/tidy-data.pdf).
However, all the column names and concept values will remain as they appear in
the SDMX file -- which is to say, not very human-readable. See the other scrip... |
"""Class that represents the network to be evolved."""
import random
import logging
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
class Network():
"""Represent a netwo... |
'''
Created on 2015年12月10日
@warning: 请务必在命令行添加选项参数,以支持不同方法的处理流程
@summary: 初始化工作,将文件的内容写入数据库
@author: suemi
'''
import sys,os
sys.path.append(".")
from optparse import OptionParser
from utils.DBUtil import DBUtil
option_0 = { 'name' : ('-s', '--start'), 'help' : '选择处理的起始位置', 'nargs' : 1 }
option_1 = { 'name' : ('-e','... |
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as _
class AnswerForm(forms.Form):
content = forms.CharField(label='Answer content', max_length=2048)
class _EmailForm(forms.ModelForm):
... |
from pget import Downloader
def sha1sum(file_name):
import hashlib
BUF_SIZE = 65536
sha1 = hashlib.sha1()
with open(file_name, 'rb') as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha1.update(data)
return sha1.hexdigest()... |
import setuptools
# Open the requirements file and dump them
with open("requirements.txt") as file:
requirements = file.read().splitlines()
# Do the same with the dev requirements
with open("requirements-dev.txt") as file:
extras = {"dev": file.read().splitlines()}
setuptools.setup(
name="tokki",
ver... |
import threading
import websocket, json, time
class CoinbaseWebsocket(threading.Thread):
def __init__(self):
# websocket.enableTrace(True)
self.ws = websocket.WebSocketApp("wss://ws-feed.exchange.coinbase.com",
on_message = self.on_message,
... |
from ipywidgets import register, Widget, DOMWidget, widget_serialization
from traitlets import (
default, TraitError,
Bool, Int, Unicode, Enum, Tuple, Instance
)
import uuid
from ._version import __version__
def id_gen():
return uuid.uuid4().urn[9:]
@register
class Node(Widget):
""" The node widget ... |
# test resources manager - parser (PM)
# test resources loader
# test Music / SOund / Font classes.
import os
import pytest
from laylib import resources as rc
@pytest.fixture
def class_resources(scope='module'):
res_class = rc.Resources('examples/data')
yield res_class
@pytest.fixture
def folder_data(scope... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sympy import cos,sin,diff,integrate,simplify,limit,solve,Symbol
x = Symbol('x')
y = Symbol('y')
# Algebraic computation
print(2*x + 3*x - y)
# Differentiates x**2 wrt. x
print(diff(x**2, x))
# differentiates cos(x) and sin(x) wrt. x
print(... |
# 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! ***
from enum import Enum
__all__ = [
'AzureSkuName',
'AzureSkuTier',
]
class AzureSkuName(str, Enum):
"""
SKU name
"""
S1 = "S1... |
from chemreps.coulomb_matrix import coulomb_matrix
import numpy as np
import pytest as pt
def test_cm():
cm_true = np.array([36.84, 23.33, 36.84, 23.38, 14.15, 36.84, 14.15,
23.38, 9.195, 36.84, 5.492, 2.762, 2.775, 2.162,
0.5, 5.492, 2.762, 2.775, 2.162, ... |
from __future__ import unicode_literals
import re
import time
from ncclient import manager
import paramiko
import xmltodict
CONNECT_TIMEOUT = 5 # seconds
class RPCClient(object):
def __init__(self, device, username='', password=''):
self.username = username
self.password = password
tr... |
from django.urls import path
from django.conf.urls import url
from django.urls import include
from rest_framework import routers
from . import views
from .viewsets import MaskDetectorViewSet
# app_name = 'api'
# router = routers.DefaultRouter()
# router.register('', MaskDetectorViewSet, basename='predict')
urlpatt... |
from abc import abstractmethod
from typing import Any, Optional, Union
from PySide6.QtWidgets import QCheckBox, QDoubleSpinBox, QHBoxLayout, QLabel, QSpinBox
from cilissa_gui.widgets.inputs.base import (
MAX_NEG_INTEGER,
MAX_POS_INTEGER,
CQInputWidget,
)
class CQNumberInputWidget(CQInputWidget):
sb:... |
#!/usr/bin/env python -O
"""
This is the test class for testing Display module algorithms and models.
"""
# -*- coding: utf-8 -*-
#
# tests.unit.TestDisplay.py is part of The RTK Project
#
# All rights reserved.
import sys
from os.path import dirname
sys.path.insert(0, dirname(dirname(dirname(__file__))) + "/r... |
import tropomi_tools as tt
import letkf_utils as lu
from datetime import datetime
timeperiod = [datetime.strptime('2019-01-01 00:00', '%Y-%m-%d %H:%M'), datetime.strptime('2019-01-02 23:59', '%Y-%m-%d %H:%M')]
histens = lu.HIST_Ens('20190102_0000',True)
histens.getLocObsMeanPertDiff(0,0)
trans = tt.TROPOMI_Translato... |
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from ohjelma.models import Song
from ohjelma.models import Track
import json
impo... |
import glob
import os
import shutil
import base64
from subprocess import Popen, PIPE
import io
import matplotlib
import imageio
from ..config import Configuration
class FrameWriter(object):
'''A writer of frames from Matplotlib figures.
This class writes out individual frames to the specified directory. No
anima... |
from wtforms import PasswordField, StringField, SelectField
from wtforms.fields.html5 import EmailField
from wtforms.validators import InputRequired
from CTFd.forms import BaseForm
from CTFd.forms.fields import SubmitField
from CTFd.forms.users import attach_custom_user_fields, build_custom_user_fields
def Registrat... |
# Command line tool for dealing with file attachments
import os
#import sys
#sys.path.append(os.path.abspath(".."))
from common_utils import *
from items_in_collection import *
# Main to accept command line and do the operation on images.
if __name__ == '__main__':
# get the command line arguments
if len(sys.a... |
def calcular_precio_producto(coste_producto):
"""
num -> num
se ingresa un numero y se obtiene el precio del producto sumandole el 50% al coste
:param coste_producto: valor numerico del coste
:return: precio del producto
>>> calcular_precio_producto(1000)
1500.0
>>> calcular_precio_... |
from django.contrib import admin
from .models import News
class NewsAdmin(admin.ModelAdmin):
date_hierarchy = 'date'
list_display = ('title', 'author', 'club', 'date')
list_filter = ('date',)
class Meta:
model = News
admin.site.register(News, NewsAdmin)
|
import chainer
import chainer.functions as F
import chainer.links as L
import numpy
from tgan2.utils import make_batch_normalization
class GeneratorConv3D(chainer.Chain):
def __init__(self, n_frames=16, z_slow_dim=256, out_channels=3):
self.n_frames = n_frames
self.z_slow_dim = z_slow_dim
... |
from werkzeug.serving import run_simple
import tuber
import sys
from .backgroundjobs import AsyncMiddleware
tuber.database.migrate()
app = tuber.app |
from django.apps import AppConfig
class SeliaMapsConfig(AppConfig):
name = 'selia_maps'
|
import os
import random
import numpy as np
from tqdm import tqdm
def self_play_history(env, agent, turn, gamma=1.0, all_purple=False):
env = env()
if all_purple:
obsv = env.update('14U24U34U44U15U25U35U45U41u31u21u11u40u30u20u10u')
else:
obsv = env.reset(agent.init_red(), agent.init_red()... |
import RPi.GPIO as GPIO
import dht11
import time
import datetime
import sys
import os
import serial
#import serialget
sys.path.append('/home/pi/proj/Adafruit_CharLCD')
from Adafruit_CharLCD import Adafruit_CharLCD
# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
lcd = Adafruit_CharLCD(rs... |
"""
Packages required
terminaltables
colorclass
"""
from schema_validation import CheckGrants as CG
from schema_validation import CheckJSON as CJ
from schema_validation import CheckTable as CT
from schema_validation import OrderFiles as OF
import os
import re
from terminaltables import SingleTable, AsciiTa... |
# Ivan Carvalho
# Solution to https://www.urionlinejudge.com.br/judge/problems/view/1222
#!/usr/bin/env python2.7
# -*- coding : utf-8 -*-
while True:
try:
a,b,c = [int(i) for i in raw_input().split()]
except EOFError:
break
entrada = raw_input().split()
paginas = 1
linha_da_vez = []
linhas = 1
for palavra i... |
import os
import shutil
from typing import Optional
import pytest
from pandas._testing import assert_frame_equal
import pandas as pd
from numpy import nan
import datacode as dc
import datacode.hooks as dc_hooks
from datacode import Variable
from tests.pipeline.base import PipelineTest, EXPECT_GENERATED_DF
from tests... |
#-*- coding: utf-8 -*-
from privtext.env import _PY_V
from random import randint
def cross_input():
if _PY_V == 2:
return raw_input()
return input()
def cross_encode(s):
if _PY_V == 2:
return s
return s.encode('utf-8')
def cross_decode(s):
if _PY_V == 2:
return s
return s.decode('utf-8')
# ... |
#!/usr/bin/env python
import os
import re
import shlex
import sys
from distutils.dep_util import newer
from shutil import which
from cx_Freeze import setup, Executable
import jinja2
#import setuptools
from setuptools import Command, find_packages
PO_FILES = 'po/*/messages.po'
class CleanCommand(Command):
"""
... |
"""Collection of nodes used in unittests.
PYTHONPATH will be automatically set so Python can find this package.
"""
import sys
import argparse
def main(argv):
parser = argparse.ArgumentParser("hello")
parser.add_argument("name", type=str, help="your name")
args = parser.parse_args(argv[1:])
print(f"... |
from nose.tools import raises
import numpy as np
from numpy.testing import assert_equal, assert_allclose
from menpo.math import dot_inplace_left, dot_inplace_right
n_big = 9182
k = 100
n_small = 99
a_l = np.random.rand(n_big, k)
b_l = np.random.rand(k, n_small)
a_r = np.ascontiguousarray(b_l.T)
b_r = np.ascontiguousa... |
from laptimize.solver import Solver
'''
Source : A global optimization method for non convex separable programming problems,
European Journal of Operational Research 117 (1999) 275±292
Authors : Han-Lin Li, Chian-Son Yu
Minimize : F0(x1) = 40*x1 + 5*(|x1-10| + x1-10) - 5*(|x1-12| + x1-12)
F0(x2) =... |
#!/usr/bin/python3.9
# Copyright (c) 2021 MobileCoin Inc.
# Copyright (c) 2021 The Forest Team
from forest.core import Bot, Message, run_bot
class TemplateBot(Bot):
async def do_template(self, _: Message) -> str:
"""
A template you can fill in to make your own bot. Anything after do_ is a / comma... |
#!/usr/bin/env python
import rospy
import sys
sys.path.append("../../")
import configparser
import numpy as np
import time
import tf
import actionlib
import signal
import std_msgs.msg
import geometry_msgs.msg
import sensor_msgs.msg
from geometry_msgs.msg import Pose
from std_msgs.msg import Float32MultiArray
from co... |
import numpy as np
import math
c = 2.9979 * pow(10,8)
#Practice test question 2 Type
def MagneticField():
ElecMax = float(input("Input the Emax (V/m): "))
angularVelocity = float(input("Input (x10^6 Rad/s): ")) * pow(10,6)
magneticField = (ElecMax/c) * pow(10,9)
print("Magnetic Field:" ... |
import pygame, sys, random
def draw_floor():
screen.blit(floor_surface, (floor_x_pos, 900))
screen.blit(floor_surface, (floor_x_pos+576, 900))
def create_pipe():
random_pipe_pos = random.choice(pipe_height)
bottom_pipe = pipe_surface.get_rect(midtop=(700, random_pipe_pos))
top_pipe = pipe_surface.... |
# 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.
"""
This implementation is based on the blog post at
https://marknelson.us/posts/2014/10/19/data-compression-with-arithmetic-coding.html
"""... |
# Volatility
# Copyright (C) 2007-2013 Volatility Foundation
#
# This file is part of Volatility.
#
# Volatility 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 2 of the License, or
# (at your o... |
import FWCore.ParameterSet.Config as cms
ct2ct = cms.EDProducer("CaloTowersReCreator",
# Weighting factor for EB
EBWeight = cms.double(1.0),
HBGrid = cms.vdouble(0.0, 2.0, 4.0, 5.0, 9.0,
20.0, 30.0, 50.0, 100.0, 1000.0),
# energy scale for each subdetector (only Eb-Ee-Hb-He interpolations a... |
import simulator
BCM = 0
IN = 0
OUT = 1
PUD_DOWN = 0
RISING = 0
def setmode(mode):
pass
def setup(pin, direction, pull_up_down=PUD_DOWN):
if direction == IN:
print("New button @pin{}".format(pin))
def add_event_detect(pin, on, callback):
print("Callback @pin{}".format(pin))
simulator.buttons... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 21 15:21:32 2020
@author: daniel
"""
import numpy as np
from cmath import sqrt
from scipy.special import sph_harm
from numpy.linalg import pinv
from matplotlib import pyplot as plt
#import shtns
class spherical:
def __init__(self, lmax):
... |
import numpy as np
import xpart as xp
import xobjects as xo
def test_basics():
for context in xo.context.get_test_contexts():
print(f"Test {context.__class__}")
particles = xp.Particles(_context=context,
mass0=xp.PROTON_MASS_EV, q0=1, p0c=7e12, # 7 TeV
x=[1e-3, 0], ... |
from __future__ import print_function
# OneWire part
try:
import ow
onewire = True
owsensorlist = []
except:
print("Onewire package not available")
onewire = False
import sys, time, os, socket
import struct, binascii, re, csv
from datetime import datetime, timedelta
# Twisted
from twisted.protocol... |
from concurrent import futures
from datetime import datetime
from typing import Tuple, Dict, List
from zipfile import ZipFile
from io import BytesIO
from collections import defaultdict
from utils.github import get_github_metadata, get_artifact
from utils.pypi import query_pypi, get_plugin_pypi_metadata
from api.s3 imp... |
#!/usr/bin/env python3
'''
Shapeless bot for MsgRoom @ Windows96.net
Shapeless bot © Diicorp95. MIT License
Windows 96 © Mikesoft. All rights reserved, except for some parts
Open-Source Part: Functional Wrap for File System (excerpt)
'''
import os.path # not implemented
def askterm(s,mgrp):
s+=' (y/n): '
i... |
"""Graph database for storing harvested data."""
from neo4j import GraphDatabase
from neo4j.exceptions import ServiceUnavailable, ConstraintError
from typing import Tuple, Dict, Set
import logging
import json
from pathlib import Path
from os import environ
import boto3
import base64
from botocore.exceptions import Clie... |
import os
from glue.core import data_factories as df
from glue.tests.helpers import requires_astropy
DATA = os.path.join(os.path.dirname(__file__), 'data')
@requires_astropy
def test_load_vot():
# This checks that we can load a VO table which incidentally is a subset of
# the one included in the tutorial.
... |
#Faça um programa que leia um ano e mostre se ele é BISSEXTO
a = int(input('Digite um ano: '))
if a % 4 == 0:
print(f'O ano {a} é BISSEXTO')
else:
print(f'O ano {a} NÃO É BISSEXTO')
|
with open("myside.txt","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if "<Media omitted>" not in line:
f.write(line)
f.truncate()
with open("otherside.txt","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if "<Media omitted>" not in... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 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... |
import unittest
from rx.core import Observable
from rx.testing import TestScheduler, ReactiveTest, is_prime
on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_completed
on_error = ReactiveTest.on_error
subscribe = ReactiveTest.subscribe
subscribed = ReactiveTest.subscribed
disposed = ReactiveTest.disposed
... |
"""
The transport decorator (~transport).
This decorator allows changes to agent response behaviour and queue status updates.
"""
from marshmallow import fields, validate
from ..models.base import BaseModel, BaseModelSchema
from ..valid import UUIDFour, WHOLE_NUM
class TransportDecorator(BaseModel):
"""Class r... |
for svc in SERVICES:
db.define_table(
'report_card_%s' % svc[0],
Field('choose_file', 'upload', uploadfield='file_data'),
Field('file_data', 'blob'),
Field('file_description', requires=IS_NOT_EMPTY()),
)
db.define_table(
'award',
YES_NO_FIELD,
)
db.de... |
#
# PySNMP MIB module MITEL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MITEL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:02:47 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, 09:23... |
# Generated by Django 3.2.8 on 2022-02-02 20:24
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ProjectSite', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Category',
... |
#-------------------------------------------------------------------------------------------
'''
#barchar and histogram of sensors
df = pd.read_csv('../data/trafico/raw_data/07-2020.csv', sep=';')
df_month = df.groupby(['id']).mean()
fig = px.bar(x = df_month.index, y=df_month['intensidad'])
fig.show()
fig = px.hist... |
#assignment one
k=float(input("\t\tENTER THE VALUE OF K = \t"))
p=(k-1)/(k+1)
print(p)
#the value of p is
#assignment two
x=int(input("\t\tENTER THE VALUE OF X = \t"))
y=int(input("\t\tENTER THE VALUE OF Y = \t"))
z=int(input("\t\tENTER THE VALUE OF Z = \t"))
result=max(min(x,y),z)
#the value stored in... |
import numpy as np
class MaskGenerator(object):
def __init__(self, h, w, rng=None):
self.h = h
self.w = w
if rng is None:
rng = np.random.RandomState(None)
self.rng = rng
def gen(self, n):
return np.ones((n, h, w))
class AllOnesMaskGenerator(MaskGenerator)... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-09-13 05:13
import core.csv_export
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tracon2018', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Pois... |
import cProfile
def test_fib(func):
lst = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
for i, item in enumerate(lst):
assert item == func(i)
print(f'Test {i} OK')
def fib_list(n):
fib_l = [None] * 1000
fib_l[:2] = [0, 1]
def _fib_list(n):
if fib_l[n] is None:
fib_l[n] =... |
import logging
from boto3 import client
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
class SSM:
"""An SSM class that provides a generic boto3 SSM client with specific SSM
functionality necessary for dspace submission service"""
def __init__(self):
self.client... |
# https://github.com/georgezlei/algorithm-training-py
# Author: George Lei
import random
def union_find(vertices, edges):
unions = [i for i in range(vertices)]
for a, b in edges:
while a != unions[a]:
a = unions[a]
while b != unions[b]:
b = unions[b]
unions[b] = a
return len([i for i i... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import JsonResponse
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.shortcuts import render
from models import *
# Create your views here.
def home(request):
texto = "banana"
template =... |
import json
import plotly
import pandas as pd
import joblib
import nltk
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from sklearn.base import BaseEstimator, TransformerMixin
from flask import Flask
from flask import render_template, request, jsonify
from plotly.graph_objs import Bar... |
import gzip
import os
from parser import Parser
path = os.getcwd() + "/corpus"
articles = ["a", "the", "an"]
pronouns = ["i", "you", "we", "it", "they", "he", "she", "my", "mine", "their", "theirs", "his",
"her", "that", "this", "us", "me", "him"]
connectives = ["in", "s", "d", "t", "by", "of",... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.10
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (3,0,0):
new_instancemethod = lambda func, inst, cls: _HLRBRep... |
# -*- coding: utf-8 -*-
"""
continuity.tests.github
~~~~~~~~~~~~~~~~~~~~~~~
Continuity GitHub tests.
:copyright: 2015 by Jonathan Zempel.
:license: BSD, see LICENSE for more details.
"""
from . import ContinuityTestCase
class GitHubCommandTestCase(ContinuityTestCase):
"""Base GitHub command... |
class A:
def f2(self, *args, a = 1):
pass
class B(A):
def f2(self, *args, a=1):
<selection>super().f2(*args, a=a)</selection>
|
# Generated from 'Movies.h'
def FOUR_CHAR_CODE(x): return x
xmlIdentifierUnrecognized = -1
kControllerMinimum = -0xf777
notImplementedMusicOSErr = -2071
cantSendToSynthesizerOSErr = -2072
cantReceiveFromSynthesizerOSErr = -2073
illegalVoiceAllocationOSErr = -2074
illegalPartOSErr = -2075
illegal... |
from part2 import test_num
def test_test_num():
assert test_num(112233) == True, "Expected 112233 to pass"
assert test_num(123444) == False, "Expected 123444 to fail"
assert test_num(111133) == True, "Expected 111133 to pass"
print("Passed!")
if __name__ == "__main__":
test_test_num()
|
# -*- coding: utf-8
from richtypo import Richtypo
from richtypo.rules import NBSP
def test_russian_simple():
r = Richtypo(ruleset='ru-lite')
text = u'Из-под топота копыт'
assert r.richtypo(text) == u'Из-под%sтопота копыт' % NBSP
def test_unicode_with_ascii_only_characters():
"""
If this test doe... |
#!/usr/bin/env python2.7
import csv
import sys
import re
from printf import printf
a = [1,2,4,5,6,9,10,13,17,19,20,36,38,39,52,68]
try:
if (sys.argv[1] == '-'):
f = sys.stdin.read().splitlines()
else:
filename = sys.argv[1]
f = open(filename, 'r')
csv = csv.reader(f)
data = list(csv)
for row i... |
__author__ = 'Aneil Mallavarapu (http://github.com/aneilbaboo)'
from datetime import datetime
import dateutil.parser
from errors import InvalidTypeException
def default_timestamp_parser(s):
try:
if dateutil.parser.parse(s):
return True
else:
return False
except:
... |
#!env python3
# Time-Stamp: <2021-04-20 19:12:36>
# Copyright 2021 Sho Iwamoto / Misho
#
# 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
# Unle... |
"""
Download data from here: https://drive.switch.ch/index.php/s/vmAZzryGI8U8rcE
Or full dataset here: https://github.com/Waller-Lab/LenslessLearning
```
python scripts/evaluate_mirflickr_admm.py \
--data DiffuserCam_Mirflickr_200_3011302021_11h43_seed11 \
--n_files 10 --save
```
"""
import glob
import os
import pa... |
import argparse
import logging
from typing import Callable
from typing import Collection
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
import numpy as np
import torch
from typeguard import check_argument_types
from typeguard import check_return_type
from espnet2.... |
#!/usr/bin/env python
import pcd8544.lcd as lcd
logo = [
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, # 0x0010 (16) pixels
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xF8, 0xFC, 0xAE, 0x0E, 0x0E, 0x06, 0x0E, 0x06, # 0x0020 (32) pixels
0xCE, 0x86, 0x8E, 0x0E,... |
import os
import errno
from ftplib import FTP
# this is used to get all tickers from the market.
exportList = []
class NasdaqController:
def getList(self):
return exportList
def __init__(self, update=True):
self.filenames = {
"otherlisted": "data/otherlisted.txt",
"na... |
import hashlib
import json
from pathlib import Path
from typing import TYPE_CHECKING
from poetry.core.packages.utils.link import Link
from .chooser import InvalidWheelName
from .chooser import Wheel
if TYPE_CHECKING:
from typing import List
from typing import Optional
from poetry.config.config import ... |
import os
import json
from json import JSONDecodeError
from .base import PersistentData
def get_key_files(alternate_key_dir=None):
key_dir = alternate_key_dir or PersistentData.config_dir
try:
keyfile_walk = next(os.walk(key_dir))
root, dirs, keyfiles = keyfile_walk
key_file_list = [o... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from polyaxon_schemas.base import BaseMultiSchema
from polyaxon_schemas.ml.layers.advanced_activations import (
ELUConfig,
LeakyReLUConfig,
PReLUConfig,
ThresholdedReLUConfig
)
from polyaxon_schemas.ml.layers.convo... |
# Importação das Livrarias
import numpy as np
import matplotlib.pyplot as plt
# TODO:
# Passo 0: Inicializar o vector de peso e o enviesamento com zeros (ou pequenos valores aleatórios).
# Passo 1: Calcular uma combinação linear das características e pesos de entrada.
# Passo 2: Aplicar a função sigmoide, que retorna ... |
#
# DecoTengu - dive decompression library.
#
# Copyright (C) 2013-2018 by Artur Wroblewski <wrobell@riseup.net>
#
# 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 Free Software Foundation, either version 3 of the License... |
from typing import Callable, Union
from pandas import DataFrame
from ..utils import load as load__
from .paths import file_paths as paths__
def load(
keys,
info: Union[bool, Callable] = False,
) -> Union[DataFrame, dict]:
if isinstance(keys, list):
paths = {
key: paths__[key]
... |
import os.path
import numpy as np
import keras.models
from keras.models import model_from_json
import tensorflow as tf
my_path = os.path.abspath(os.path.dirname(__file__))
digit_model_json = os.path.join(my_path, "../../static/models/digit_model.json")
digit_model_h5 = os.path.join(my_path, "../../static/models/digit... |
#ucapan selamat tahun baru
ucapan_happynewyear = ['hello world', 'selamat tahun baru', 'stay safe be productive', 'happy new year', 'Shinen akemashite omedetou gozaimasu 新年あけましておめでとうございます', 'keep spirit and enjoy life']
Mywish_newyear2022 = ['keep productive', 'improving grade', 'accept on state university']
#prin... |
#Licensed under Apache 2.0 License.
#© 2020 Battelle Energy Alliance, LLC
#ALL RIGHTS RESERVED
#.
#Prepared by Battelle Energy Alliance, LLC
#Under Contract No. DE-AC07-05ID14517
#With the U. S. Department of Energy
#.
#NOTICE: This computer software was prepared by Battelle Energy
#Alliance, LLC, hereinafter the Cont... |
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from torch.autograd import Function
from torch.autograd import Variable
from utils.box_utils import decode
# test_RFB.py中被调用,生成的detector对象,结合net输出的out(forward中拆分为loc + conf,结合RFBNet结构,
# 可以发现是一个全卷积的feature map,可以结合multibox函数理解),conf就是预测的分类得分,
# lo... |
import textwrap
import datetime
import glob
from collections import Counter
from .getApi import getApi
from .Exceptions import NoTownError
def funcShelves(townName):
# API取得部
town = getApi("town", "https://so2-api.mutoys.com/master/area.json")
sale = getApi("sale", "https://so2-api.mutoys.com/json/sale/al... |
from __future__ import absolute_import
from datetime import datetime
from django.conf import settings
from django.contrib import admin
from django.contrib.admin import helpers
from django.contrib.admin.util import (display_for_field, label_for_field,
lookup_field, NestedObjects)
from django.contrib.admin.views.ma... |
# %%
import cv2
import os
import argparse
import time
import func
import numpy as np
# %% args
parser = argparse.ArgumentParser()
parser.add_argument('-I','--image',
default='100',
help='import image type, such as 100 or Die')
# 輸入圖片類型,範例為'100'及'Die'
parser.add_... |
from redis import Sentinel, Redis
from app.core.config import settings
import app.core.logging
sentinel = Sentinel([(settings.REDIS_SENTINEL_SERVER, settings.REDIS_SENTINEL_PORT)], socket_timeout=0.1)
masters = sentinel.discover_master('mymaster')
slaves = sentinel.discover_slaves('mymaster')
master = sentinel.mas... |
import os
import csv
from dream_funcs import DeepDream
from PIL import Image, ImageChops
import numpy as np
# deepdream setup
blend_frames = True
alpha_step = 0.5
layer = 'mixed5b_1x1'
channel = 314
n_iter = 30
step = 1.5
octaves = 8
octave_scale = 1.5
dd = DeepDream(layer, (lambda T: T[:,:,:,channel]))
# file data... |
# -*- coding: utf-8 -*-
"""
Defines earth model objects.
:copyright: 2017 Agile Geoscience
:license: Apache 2.0
"""
import re
import os
import copy
import numpy as np
from bs4 import BeautifulSoup
import vtk
from vtk.util.numpy_support import vtk_to_numpy
import matplotlib.pyplot as plt
from bruges.transform import d... |
#!/usr/bin/python
from flask import Flask, send_file
app = Flask(__name__)
@app.route('/image')
def get_image():
filename = 'sid.png'
return send_file(filename, mimetype='image/png')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.