content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import pytest
from pySnowRadar.timefunc import utcleap
def test_utcleap_invalid():
with pytest.raises(Exception):
result = utcleap('a')
def test_utcleap_valid():
true_time = 1092121230.0
assert utcleap(1092121243.0) == true_time | python |
import argparse
import csv
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s | [%(levelname)s] : %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
parser = argparse.ArgumentParser()
parser.add_argument("--package_list",
type=argparse.FileType('r'),
help="Path to the file t... | python |
# Generated by Django 3.0.1 on 2020-02-10 02:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipes', '0001_initial'),
('main', '0016_auto_20191222_2333'),
]
operations = [
migrations.AlterField(
model_name='prof... | python |
#Functions and some global variables were moved here simply to clean up main.py.
import re #import regular expressions
import string
import obj_wordlist
#Limit on the length of generated sentences.
#TODO. Later you could do a depth-limited, depth-first search for a path to a period to end the sentence.
sentenceLengt... | python |
# Generated by Django 2.2.7 on 2020-01-15 14:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('web', '0013_auto_20200108_2257'),
]
operations = [
migrations.AlterField(
model_name='article',
name='src_url',
... | python |
'''
最小体力消耗路径
你准备参加一场远足活动。给你一个二维 rows x columns 的地图 heights ,其中 heights[row][col] 表示格子 (row, col) 的高度。
一开始你在最左上角的格子 (0, 0) ,且你希望去最右下角的格子 (rows-1, columns-1) (注意下标从 0 开始编号)。
你每次可以往 上,下,左,右 四个方向之一移动,你想要找到耗费 体力 最小的一条路径。
一条路径耗费的 体力值 是路径上相邻格子之间 高度差绝对值 的 最大值 决定的。
请你返回从左上角走到右下角的最小 体力消耗值 。
提示:
rows == heights.length
columns ... | python |
lista = pares = impares = []
while True:
lista.append(int(input('Digite um número: ')))
resp = ' '
while resp not in 'SN':
resp = str(input('Deseja continuar? [S/N] ')).strip().upper()[0]
if resp == 'N':
break
for c, v in enumerate(lista):
if v % 2 == 0:
pares.append(v)
e... | python |
from PyQt5.QtCore import QUrl
from PyQt5.QtMultimedia import (QMediaContent, QMediaPlaylist, QMediaPlayer, QAudio)
import mutagen.mp3
import os
import files
import util
def is_music_file(file: str):
return os.path.isfile(file) and file.lower().endswith('.mp3')
class InvalidFile(Exception):
pass
# noinsp... | python |
import os, sys, json, unittest, logging, uuid, decimal, datetime, time
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
import aurora_data_api # noqa
from aurora_data_api.mysql_error_codes import MySQLErrorCodes # noqa
from aurora_data_api.postgresql_error_codes import PostgreSQLErrorCodes # noqa
... | python |
"""Abfallplus sensor platform."""
from homeassistant import config_entries, core
import babel.dates
from homeassistant.components.sensor import (
SensorEntity,
SensorEntityDescription,
)
from .const import DOMAIN
async def async_setup_entry(
hass: core.HomeAssistant,
config_entry: config_entries.Conf... | python |
from ctapipe.core import Component
class IntensityFitter(Component):
"""
This is the base class from which all muon intensity,
impact parameter and ring width fitters should inherit from
"""
def fit(self, x, y, charge, center_x, center_y, radius, times=None):
"""
overwrite this me... | python |
import os
import subprocess
from gen_tools import run_ftool, ftool_mp, run_ftool2
import argparse
import numpy as np
import time
from astropy.table import Table
import pandas as pd
def run_ftjoin_mp(dname, dname2, fnames, nproc):
ftool = "ftjoin"
arg_lists = []
for fname in fnames:
arg_list = [... | python |
import os
import easypost
from dotenv import load_dotenv
# Retrieve a list of paginated records such as scanforms or shipments.
# Because EasyPost paginates lists of records at a max of 100 items, you may at times need to iterate the pages.
# This tool will combine all records between two dates and print their IDs an... | python |
#!/usr/bin/env python
import os
import re
import plotly
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
import pandas as pd
import numpy as np
from sklearn.datasets import load_wine
from shutil import copyfile
def loadWineDataSet():
data = load_wine()... | python |
from telegram.ext import Updater
import random
from datetime import datetime
import requests
import pyowm
import re
import os
from flask import Flask, request
import logging
import apiai
import json
import re
from on_event.work.text import *
from on_event.errors import *
def press_f(update, context):
if(update.me... | python |
import numpy as np
from unittest import TestCase
from aspire.source import SourceFilter
from aspire.source.simulation import Simulation
from aspire.utils.filters import RadialCTFFilter
from aspire.estimation.noise import WhiteNoiseEstimator
import os.path
DATA_DIR = os.path.join(os.path.dirname(__file__), 'saved_test... | python |
from adafruit_circuitplayground.express import cpx
while True:
# Left returns True. Right returns False.
cpx.red_led = cpx.switch
| python |
from collections import defaultdict
import logging
from typing import Dict
import ray
from horovod.ray.utils import map_blocking
from horovod.ray.worker import BaseHorovodWorker
logger = logging.getLogger(__name__)
def create_placement_group(resources_per_bundle: Dict[str, int],
num_bundl... | python |
from pathlib import Path
from django.conf import settings
from django.db.models import ImageField, FileField, Q
from django.contrib.contenttypes.models import ContentType
def move_media(*names, back=False):
"""Moves media files to or from a temporary directory."""
old, new = ('temp', '') if back else ('', 't... | python |
# -*- coding: utf-8 -*-
from calysto.graphics import *
from calysto.display import display, clear_output
#image_width=512
image_width=0
canvas=None
color=None
rect=None
#初期化
def init(size, r, g, b):
global image_width
global canvas
global color
global rect
image_width=size
c... | python |
#! /usr/bin/env python
################################################################################
# RelMon: a tool for automatic Release Comparison
# https://twiki.cern.ch/twiki/bin/view/CMSPublic/RelMon
#
#
# ... | python |
# Copyright (c) 2013 Ian C. Good
#
# 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, modify, merge, publish, distrib... | python |
# Copyright 2021 AIPlan4EU project
#
# 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 wri... | python |
import wiringpi2 as wiringpi
import time
from time import sleep
import datetime
import sys
wiringpi.wiringPiSetup()
wiringpi.pullUpDnControl(16, 1) # Setup sensor input
wiringpi.pinMode(1, 3)
# Function for getting the current speed
def getSpeed():
currentTime = int(time.time())
currentTime = currentTime + 2
ne... | python |
import time
import numpy
import matplotlib.pyplot as plt
from pyscf import gto, scf
import scipy
from scipy.optimize import minimize
import jax.numpy as jnp
from jax import grad, jit, random
from jax.config import config
config.update("jax_enable_x64", True)
import adscf
key = random.PRNGKey(0)
x = []
y = []
x_a... | python |
# https://oj.leetcode.com/problems/word-ladder/
import heapq
class Solution:
# @param start, a string
# @param end, a string
# @param dict, a set of string
# @return an integer
def ladderLength(self, start, end, dict):
# BFS2
self.minLen = self.bfs2(start, end, dict)
# DFS
# self.minLen = ... | python |
#!/usr/bin/env python
import sys,socket,getopt,threading,subprocess
listen = False
command = False
upload = False
execute = ""
target = ""
upload_dest = ""
port = 0
def banner():
print "[***] NetCat p19 [***]"
print "... | python |
import json
import sys
# Enter the filename you want to process
file = sys.argv[1]
filename = f'{file}_changedFunctions.json'
print(f'Reading from filename {filename}')
with open(filename) as f:
init_database = json.load(f)
# Print total number of examples in dataset
print(f'Total number of functions (including all ... | python |
import os
from io import BytesIO
import tarfile
from six.moves import urllib
import matplotlib
matplotlib.use('Agg')
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image
import tensorflow as tf
flags = tf.app.flags
FLAGS = flags.FLAGS
# flags.DEFINE_string('mod... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
nodeenv
~~~~~~~
Node.js virtual environment
:copyright: (c) 2011 by Eugene Kalinin
:license: BSD, see LICENSE for more details.
"""
nodeenv_version = '0.3.5'
import sys
import os
import time
import logging
import optparse
import subprocess
import... | python |
#
# Copyright (c) 2017, Massachusetts Institute of Technology 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 o... | python |
#!/usr/bin/env python
from setuptools import setup, find_packages
try:
README = open('README.rst').read()
except:
README = None
try:
REQUIREMENTS = open('requirements.txt').read()
except:
REQUIREMENTS = None
setup(
name='spotify2piratebay',
version="0.1",
description='Download your Spoti... | python |
from django.urls import include, path
from django.contrib import admin
from config import views
urlpatterns = [
path('admin/', admin.site.urls),
path('health/', views.health),
path('', include('engine.urls', namespace="engine")),
]
| python |
import transmogrifier.models as timdex
from transmogrifier.helpers import generate_citation, parse_xml_records
def test_generate_citation_with_required_fields_only():
extracted_data = {
"title": "A Very Important Paper",
"source_link": "https://example.com/paper",
}
assert (
genera... | python |
def findRanges(nums):
sol = []
if len(nums) == 0 or len(nums) == 1:
return nums
# temp = nums
# [temp.append(x) for x in nums if x not in temp]
i,j = 0,1
prev, cur = nums[i],nums[j]
while j < len(nums):
if prev+1 == cur or prev == cur:
prev = cu... | python |
import torch
def select_optimizer(model, config):
optimizer = None
if config["optimizer"] == "SGD":
optimizer = torch.optim.SGD(model.parameters(), lr=config["learning_rate"])
elif config["optimizer"] == "Adam":
optimizer = torch.optim.Adam(model.parameters(), lr=config["learning_rate"])
... | python |
#!/usr/bin/env python
import numpy as np
import math
import random
import time
# This was created to separate make_data and the model and the solver
rnd = np.random
#rnd.seed(0)
#This version is changed according the JMetal
def make_data(U1,V1,K1,N1,Psi_u1,Psi_u2,Phi_u1,Phi_u2,B_u1,B_u2,r_u1,tau_v1,tau_v2,s... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created in September 2020
@author: karliskanders
Functions and classes for generating and analysing career transition recommendations
"""
import pandas as pd
import numpy as np
import pickle
from time import time
import yaml
import os
from ast import literal_eval
fr... | python |
from setuptools import setup
setup(name='docx-mailmerge-conted',
version='0.5.1',
description='Performs a Mail Merge on docx (Microsoft Office Word) files',
long_description=open('README.rst').read(),
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Langu... | python |
# This python script scrapes data from the scanA.csv and
# scanB.csv files created by the python_cbc_building module
# and stores this scraped data in the SMAP archiver.
#
import os
from string import *
import time
from pytz import timezone
from smap import driver, util
# SMAP heading
smapHeading = "ORNL/cbc"
# Data... | python |
# Copyright 2021-2022 NVIDIA Corporation
#
# 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 ... | python |
# -*- coding: utf-8 -*-
# --------------------------------------------------------
# RefineDet in PyTorch
# Written by Dongdong Wang
# Official and original Caffe implementation is at
# https://github.com/sfzhang15/RefineDet
# --------------------------------------------------------
import sys
import torch
import torc... | python |
# *****************************************************************************
# Copyright 2004-2008 Steve Menard
#
# 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://... | python |
# lista = [2, 4, 2, 2, 3, 3, 1]
def remove_repetidos(lista):
lista_aux = []
for element in lista:
if element not in lista_aux:
lista_aux.append(element)
return sorted(lista_aux)
# print(remove_repetidos(lista))
| python |
FTX_MAX_REQUESTS_RESET = "FTX_MAX_REQUESTS_RESET"
FTX_TOTAL_REQUESTS = "FTX_TOTAL_REQUESTS"
API_URL = "https://ftx.com/api"
MAX_RESULTS = 200
MIN_ELAPSED_PER_REQUEST = 1 / 30.0 # 30 req/s
# For MOVE
BTC = "BTC"
BTCMOVE = "BTC-MOVE"
| python |
import uuid
from django.conf import settings
from django.contrib.auth.hashers import make_password, check_password
from django.contrib.auth.models import (User)
from django.utils.module_loading import import_module
from authy_me.models import AuthenticatorModel
def is_int(s):
"""
Checks if the content is of... | python |
# Original code from: https://github.com/m4jidRafiei/Decision-Tree-Python-
#
# Modified by a student to return the Digraph object instead of rendering it automatically.
# Modified to avoid error of mis-identification of graphviz nodes. Although I used a random
# generation and probabilistic cosmic rays might introduce ... | python |
#Roman numerals are: [i v x l c d m]
def stringer (x):
number_string = str(x)
if number_string[0] /= 0:
a = number_string[0];
elif
continue:
if number_string[1] /= 0:
b = number_string[1];
elif
continue:
if number_string[2] /= 0:
c = number_string[2];
elif
cont... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Generates a scoring function from worm data that can be fed a time and
distance gap to predict connected worm tracks.
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals)
import six
from six.moves import (zip, filter, map, r... | python |
import unittest
import os
import v1
from fs import TestApi
class V1FormatEntryTest(unittest.TestCase):
def setUp(self):
self.fs = TestApi(cwd = '/a/b/c')
def test_with_absolute_path(self):
entry = v1.format_entry('vdir', '/root/some/path:one/dir', self.fs)
self.assertEqual(entry, ('/root/some/path',... | python |
from __future__ import absolute_import, division, print_function
import datetime
import os
import shutil
class Logger(object):
def __init__(self):
self.file = None
self.buffer = ''
def __del__(self):
if self.file is not None:
self.file.close()
def set_log_file(self, f... | python |
from kivy.uix.button import Button
from streetlite.panel.sequence.sequence import Sequence
class SequenceButton(Button):
def __init__(self, start, end, **kwargs):
super().__init__(**kwargs)
is_default = self.text == "Default"
self.sequence = Sequence(is_default, start, end)
| python |
import quizzer.serializers.assessment_json_serializer as json_serializer
import quizzer.serializers.assessment_xml_serializer as xml_serializer
__author__ = 'David Moreno García'
def serialize_grades(grades, format):
"""
Returns an string with the representation of the grades in the desired format.
:par... | python |
# Generated from sdp.g4 by ANTLR 4.8
# encoding: utf-8
from __future__ import print_function
from antlr4 import *
from io import StringIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2")
buf.write(u"\u0102\u0403\b\1\4\2\t\2... | python |
import torch
import torch.nn as nn # for network
import torch.nn.functional as F # for forward method
drop_out_value = 0.1
class Network(nn.Module):
def __init__(self):
super(Network,self).__init__() # extending super class method
# Input block
self.convblock_input= nn.Sequential(
... | python |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt4 (Qt v4.8.7)
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore
qt_resource_data = "\
\x00\x00\x03\x92\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x1f\x00... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
class TestTest(unittest.TestCase):
# @unittest.skip("skip this test")
def test_bench(self):
from tocoli.test import bench, Bencher
# Test 1 - add()
def add(a, b):
return a + b
res = bench(add, 2, 3)
... | python |
import os
def start_preparation_st(test_data_path, data_root, src_lang, tgt_lang):
os.system(test_data_path +
" --data-root " + data_root +
" --vocab-type char"
" --src-lang " + src_lang +
" --tgt-lang " + tgt_lang)
def start_preparation_asr(test_data_path... | python |
from .query import *
| python |
# -*- coding: utf-8 -*-
import base64
import json
from watson_developer_cloud import ConversationV1
class FarmerConversation:
def __init__(self):
pass
def converse(self, text):
conversation = ConversationV1(
username='a5f91c9c-12e8-4809-9172-6f68ed4b01d3',
password='... | python |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------------------... | python |
import re
def do_selection_sort(in_list: list):
for i in range(len(in_list)):
print(f'Step {i}: {in_list}')
minimum = i
for j in range(i, len(in_list)):
if in_list[j] < in_list[minimum]:
minimum = j
in_list[i], in_list[minimum] = in_list[mini... | python |
# standard library
import warnings
import pdb
# 3rd party library
from torch import nn as nn
# mm library
from mmcv.cnn import build_conv_layer
# gaia lib
from gaiavision.core import DynamicMixin
from gaiavision.core.bricks import build_norm_layer, DynamicBottleneck
class DynamicResLayer(nn.ModuleList, DynamicMixi... | python |
import csv
import os
# from utility import uprint
import pandas as pd
def extract_stat_names(dict_of_stats):
"""Extracts all the names of the statistics
Args:
dict_of_stats (dict): Dictionary containing key-alue pair of stats
"""
stat_names = []
for key, val in dict_of_stats.items():
... | python |
# Created by wangmeng at 2020/11/19
from toolkit.models.base_host import BaseHost
from toolkit.models.host import Host
from toolkit.models.operator import HostOperator
async def get_host_info_by_label(label: str) -> dict:
operator = HostOperator('localhost', 27017)
host_info = await operator.get_host_info_by_... | python |
# -*- coding: UTF-8 -*-
from redis import ConnectionPool, Redis
from redlock import RedLockFactory
class RedisDB(object):
"""
Redis数据库连接池和Redis分布式锁统一获取入口,当前Redis只支持单节点,可以通过简单修改支持Redis集群
"""
def __init__(self, nodes):
assert len(nodes) > 0
self.__nodes = nodes
self.__redis_pool ... | python |
import sys
import random
from math import sqrt, log
import subprocess32, struct
U = 0.5
C = sqrt(2)
samples = 10
max_rounds = 100
total = 0
max_iterations = 10
class Node():
def __init__(self, path):
assert(path)
self.addr = path[-1]
self.path = path
self.children = {... | python |
from .data_catalog import DataCatalog
from .deltalake import PyDeltaTableError, RawDeltaTable, rust_core_version
from .schema import DataType, Field, Schema
from .table import DeltaTable, Metadata
from .writer import write_deltalake
| python |
with open("even_more_odd_photos.in") as input_file:
N = int(input_file.readline().strip())
breed_IDs = list(map(int, input_file.readline().strip().split()))
odds = 0
evens = 0
for i in breed_IDs:
if i%2 == 0:
evens+=1
else:
odds+=1
groups = 0
if odds == 0:
groups = 1
elif evens == ... | python |
#coding=utf-8
'''
Created on 2015-10-22
@author: zhangtiande
'''
from gatesidelib.common.simplelogger import SimpleLogger
from model_managers.model_manager import ModelManager
class LoggerManager(ModelManager):
'''
classdocs
'''
def all(self):
return super(LoggerManager,self).get_qu... | python |
#!/usr/bin/env python3
import socket
# HOST = '127.0.0.1' # Standard loopback interface address (localhost)
HOST = '192.168.0.100' # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
#PORT = 8000
hostname = socket.gethostname()
# getting the I... | python |
#!/usr/bin/env pybricks-micropython
from spockbots.gyro import SpockbotsGyro as Gyro
from spockbots.motor import SpockbotsMotor
import time
def run_crane():
"""
lower the block from the crane
"""
robot = SpockbotsMotor()
robot.debug = True
robot.setup()
robot.colorsensors.read()
pri... | python |
import bottle
import model
import pyperclip
gesla = model.Geslo(model.DATOTEKA_S_S)
with open("skrivnost.txt") as f:
SKRIVNOST = f.read()
@bottle.get("/")
def index():
return bottle.template("index.tpl")
@bottle.post("/geslo/")
def novo_geslo():
st = bottle.request.forms.get('prva') or 0
mc = bot... | python |
import os
import traceback
from argparse import ArgumentParser
import sys
import signal
from anime_automove.feature import Learn, Execute, Remove, Show
from anime_automove.util.app import Config
from anime_automove.util.dal import init
def main():
"""Run the main program"""
# ARGS
#
parser = Argum... | python |
import argparse
import base64
import glob
import io
import json
import os
import random
import pycocotools
import cv2
import imageio
from PIL import Image, ImageColor, ImageDraw
import numpy as np
import visvis as vv
from pycocotools import mask
from skimage import measure
CAT_TO_ID = dict(egg=1, blob=2)
CAT_TO_COLOR ... | python |
import numpy as np
"""
Hidden Markov Model using Viterbi algorithm to find most
likely sequence of hidden states.
The problem is to find out the most likely sequence of states
of the weather (hot, cold) from a describtion of the number
of ice cream eaten by a boy in the summer.
"""
def main():
np.set_printoptio... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from django.conf import settings
from django.utils.timezone import now
from django.utils.translation import activate, override
from aldryn_newsblog.models import Article
from cms import api
from . import NewsBlogTestCase, NewsBlogTransaction... | python |
# ==============================================================================
# Copyright 2018-2020 Intel Corporation
#
# 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://ww... | python |
# Copyright 2018 AT&T Intellectual Property. All other 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... | python |
from Mask_RCNN.mrcnn.utils import Dataset
from Mask_RCNN.mrcnn.utils import extract_bboxes
from Mask_RCNN.mrcnn.visualize import display_instances
from numpy import expand_dims
from numpy import mean
from mrcnn.config import Config
from mrcnn.model import MaskRCNN
from mrcnn.utils import Dataset
from mrcnn.utils impor... | python |
# -*- coding: utf-8 -*-
import os
def count_files(path):
"""Count number of files in a directory recursively.
Args:
path (str): Directory.
Returns:
int: Return number of files.
"""
count = 0
for root, dirs, files in os.walk(path):
for f in files:
count +=... | python |
# Generated by Django 2.1.7 on 2019-03-20 14:14
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('internet_nl_dashboard', '0003_uploadlog'),
]
operations = [
migrations.AddField(
model_name='up... | python |
from numpy import double
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
Multi-agent Modules
"""
# define the actor network
class actor_shared(nn.Module):
def __init__(self, env_params, identification = True):
# Note: id for agent is important
super(actor_shared, self).__in... | python |
"""
calendarimg.py
获取单向历,存储于本地
调用方式: calendarAcquirer.getImg()
write on 2018.09.15
"""
__author__ = "Vincent Zhang"
import pgconfig
import usrconfig
import requests
import json
import re
import time
import os
class calendarAcquirer:
@staticmethod
def getUrl():
... | python |
from flask import Flask, request
import os
app = Flask(__name__)
@app.route("/upload", methods=["POST"])
def upload():
file = request.files.get("file_name")
if file is None:
return "None file"
localfile = open("demo.png", "wb")
data = file.read()
localfile.write(data)
localfile.close(... | python |
from flask import Blueprint, render_template, request
from users.models import SessionModel
from utils.http import require_session
application = Blueprint('dashboard', __name__)
@application.route("/dashboard/", methods=['GET'])
@require_session()
def get_list(session):
return render_template('index.html', ... | python |
from flask import Flask, send_file, send_from_directory, make_response, request, abort, session, redirect, jsonify
import re, threading, datetime, time, os, random, string, base64
from flask_pymongo import PyMongo
# 此程序只能在64位机器上运行,否则可能溢出
password = "password" # when deploy, change this !!!
imagepath = "/home/hw... | python |
from .authentication import *
from .external_authentication import *
from .guest_authentication import *
from .key_authentication import *
from .plain_authentication import *
from .transport_authentication import *
| python |
import json, os, re, sublime, sublime_plugin, time
class PhpNamespaceMonkey():
namespaces = {}
def addBoilerplate(self, view):
settings = sublime.load_settings('PhpNamespaceMonkey.sublime-settings')
if not view.file_name() or not self.isPhpClassFile(view.file_name()) or view.size(): return
... | python |
# Given a string text,
# you want to use the characters of text to form as many instances of the word "balloon" as possible.
# You can use each character in text at most once.
# Return the maximum number of instances that can be formed.
# Example 1:
# Input: text = "nlaebolko"
# Output: 1
# Example 2:
# Input: text... | python |
import pytest
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.permissions import IsAuthenticated
from rest_framework.exceptions import PermissionDenied
from ..decorators import resolver_permission_classes
from .test_views import url_string, response_json
class user(object):
... | python |
import matplotlib.pyplot as plt
import numpy as np
import os
import random
class City:
def __init__(self, x, y):
self.x = x
self.y = y
def distance_to(self, city):
x_dist = abs(self.x - city.x)
y_dist = abs(self.y - city.y)
distance = np.sqrt(x_dist ** 2 + y_dist ** 2... | python |
import rasterio as rio
import numpy as np
def rio_read_all_bands(file_path):
with rio.open(file_path, "r") as src:
meta = src.meta
n_bands = src.count
arr = np.zeros((src.count, src.height, src.width), dtype=np.float32)
for i in range(n_bands):
arr[i] = src.read(i+1).as... | python |
# Django Rest Framework
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
# Models
from sunnysouth.marketplace.models.categories import Category
# Serializers
from sunnysouth.marketplace.serializers.categories import CategoryModelSerializer
class CategoryViewSet(viewsets.Mod... | python |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | python |
import unittest
from routes import request_config, _RequestConfig
from routes.base import Route
class TestBase(unittest.TestCase):
def test_route(self):
route = Route(None, ':controller/:action/:id')
assert not route.static
def test_request_config(self):
orig_config = request_confi... | python |
#!/usr/bin/env python
# encoding=utf-8
# Created by andy on 2016-08-03 18:38.
import pickle
import common
import utils
__author__ = "andy"
a = ['a','b','c','d']
print (a.index('d'))
#for batch in xrange(common.BATCHES):
# train_inputs, train_targets, train_seq_len = utils.get_data_set('train', batch*common.BATCH_... | python |
import unittest
from dxtrack import dxtrack
class TestFramework(unittest.TestCase):
def test_configure(self):
"""
Test the simple base case
"""
default_metadata = {'default': 'metadata'}
dxtrack.configure(
context='test_error_track',
stage='test',
... | python |
from datetime import datetime
# Three log levels, ERROR enforced by default
messages = {
0: "ERROR",
1: "INFO",
2: "DEBUG",
}
class logger:
def __init__(self, level, logfile=None):
if logfile:
self.logfile = open(logfile, "wb")
else:
self.logfile = None
... | python |
from .base_config import base_config, get_config
new_config = {
'exp_name': "protonet_default",
'trainer': 'prototypical',
'num_training_examples': 14000,
'n_support': 5,
'n_query': 20,
'n_test_query': 100,
'freeze_until_layer': 10,
}
config = get_config(base_config, new_config) | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.