content stringlengths 5 1.05M |
|---|
"""OpenID Extension modules."""
from __future__ import unicode_literals
__all__ = ['ax', 'pape', 'sreg']
|
import logging
import pickle
logger = logging.getLogger(__name__)
LOAD_FROM_CONFIG_KEY = "checkpoint_to_load_from"
def after_init_load_policy_checkpoint(policy, observation_space=None, action_space=None, trainer_config=None):
"""
This function is to be given to a policy template (to the after_init argument)... |
from smtplib import SMTPRecipientsRefused
from outbox import Outbox, Email, Attachment
from model import Account
def send(account: Account, to: str, subject: str, body: str, attachment,
attachment_name):
if not body:
raise EmptyBody
with Outbox(server=account.smtp_host, port=account.smtp_p... |
from rest_framework import serializers
from .models import Task
class TaskSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Task
fields = ('id', 'title', 'description', 'date', 'time') |
import sys
import cgi
import time
import string
import re
import logging
import functools
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
from .application import application_instance
from .transaction import Transaction, current_transaction
from .function_trace import FunctionTrace
f... |
"""Set Static Variable in PPO."""
GAMMA = 0.99
LAM = 0.95
BATCH_SIZE = 512
|
import pandas as pd
import numpy as np
import copy
import pickle
from datetime import datetime,timedelta
import os
import multiprocessing
import random
data_path = '../data/'
TEST = True
if TEST:
df = pd.read_csv(data_path + '201407_new.csv',sep = ';')
else:
data_path = '../data/'
df1 = pd.read_csv(da... |
"""The NZBGet integration."""
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_SCAN_INTERVAL, Platform
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.update_... |
import torch, time, numpy as np
import utils_misc
class ScorerWrapper:
def __init__(self, scorers, scoring_method="logsum", max_batch_size=100, use_caching=False):
assert scoring_method in ["sum", "product", "logsum"], "Unrecognized `scoring_method`"
self.scorers = scorers
self.scoring_met... |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created: Tue 4. Sep 12:12:57 2018
# by: The Resource Compiler for PySide (Qt v4.8.7)
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore
qt_resource_data = b"\x00\x00\x01,\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\x00\x00@\x0... |
####################################
# File name: Train_Checkers_AI.py
# Author: BenjaminBeggs
#
# Description: Master Python file that bridges data outputs between
# the 4 Machine-Learning modules (PerformanceSystem, ExperimentGenerator,
# Critic, Generalizer) and manages the training process for the AI.
#
# Every 1... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'license.ui'
#
# Created: Fri Jan 16 01:13:07 2015
# by: PyQt4 UI code generator 4.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except Attrib... |
"""
Three Number Sum
Write a function that takes a non-empty array of distinct integers and an integer representing
a target sum. The function should find all triplets in the array that sum up to the target sum and return
a two-dimensional array of all these triplets. The numbers in each triplet should be ordered i... |
import os,time,sys
__PATH__ = os.path.dirname(os.path.abspath(__file__)).replace('\\','/')
sys.path.append(os.path.dirname(__PATH__))
from auana import *
# search .wav file
def test(dir_audio0):
st = Storage()
File_num = 0
NUM = 0
NUMM = 0
SUM = 0
ab = time.clock()
for parent, dirnames, filenames in os.wal... |
from django.conf.urls.defaults import patterns, url
import django.views.generic as gen_views
from main.models import *
urlpatterns = patterns('',
url(r'^$', 'main.views.home', name = 'home'),
)
|
from boto.resultset import ResultSet
class Template(object):
def __init__(self, connection=None):
self.connection = connection
self.description = None
self.template_parameters = None
def startElement(self, name, attrs, connection):
if name == "Parameters":
self.temp... |
#!/usr/bin/env python3
# Copyright 2020-present NAVER Corp. Under BSD 3-clause license
import argparse
import logging
from functools import lru_cache
from typing import Optional
import torch
from tqdm import tqdm
import os
import path_to_kapture_localization # noqa: F401
import kapture_localization.utils.logging
fro... |
import typing
import pkg_resources
from hyperscan._hyperscan import *
__version__ = pkg_resources.get_distribution('hyperscan').version
class ExpressionExt(typing.NamedTuple):
flags: int
min_offset: int = 0
max_offset: int = 0
min_length: int = 0
edit_distance: int = 0
hamming_distance: int... |
import setuptools
with open('requirements.txt') as f:
requires = [line.strip() for line in f.readlines()]
setuptools.setup(
name="pubsub",
version="0.1.0",
url="https://github.com/mttr/pubsub",
author="Matt Rasmus",
author_email="mattr@zzntd.com",
description="A simple PubSub server impl... |
"""Various utilities common to IPython release and maintenance tools.
"""
from __future__ import print_function
# Library imports
import os
import sys
from distutils.dir_util import remove_tree
# Useful shorthands
pjoin = os.path.join
cd = os.chdir
# Constants
# SSH root address of the archive site
archive_user = ... |
#!/usr/bin/python3
import argparse
import os
import json
import shutil
def loadIOC(filename):
conf = {}
with open(filename) as f:
while True:
line = f.readline().strip()
if not line:
break
if line[0] == '#':
continue
vals ... |
from env_wrapper import DIAYN_Skill_Wrapper
import gym
import pybulletgym
from stable_baselines3 import SAC
total_timesteps = 10000
num_skills = 100
env = gym.make('Walker2DMuJoCoEnv-v0')
env = DIAYN_Skill_Wrapper(env,num_skills=num_skills)
agent = SAC("MlpPolicy", env, verbose=1,tensorboard_log="./tensorboard").learn... |
import pygame
import math
class CmdBar():
def __init__(self,dim_x,dim_y,pos_x,pos_y,surf,active=False,text=""):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((dim_x,dim_y))
#pygame.draw.circle(self.image, (255,0,0), (50,50), 50, 2)
self.rect = self.image... |
class Integrator:
"""Integrator for a system of first-order ordinary differential equations
of the form \dot x = f(t, x, u).
"""
def __init__(self, dt, f):
self.dt = dt
self.f = f
def step(self, t, x, u):
raise NotImplementedError
class Euler(Integrator):
def step(self,... |
#!/usr/bin/python
# ---------------------------------------------------------------------------
# File: mipex1.py
# Version 12.8.0
# ---------------------------------------------------------------------------
# Licensed Materials - Property of IBM
# 5725-A06 5725-A29 5724-Y48 5724-Y49 5724-Y54 5724-Y55 5655-Y21
# Copyr... |
from googleapiclient import errors
from googleapiclient.http import MediaFileUpload
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
def get_authenticated(SCOPES, credential_file, service_name='drive',
api_version='v3'):
# The... |
from LSP.plugin.core.settings import read_client_config, update_client_config
from LSP.plugin.core.views import get_uri_and_position_from_location
from LSP.plugin.core.views import to_encoded_filename
from os import environ
from os.path import dirname, pathsep
from unittesting import DeferrableTestCase
test_file_path ... |
# Copyright 2016 Google 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
#
# Unless required by applicable law or ag... |
"""
Users are those with access to InfluxDB.
To grant a user permission to access data, add them as a member of an organization
and provide them with an authentication token.
"""
from influxdb_client import UsersService, User
class UsersApi(object):
"""Implementation for '/api/v2/users' endpoint."""
def __... |
#script that inside a directory, get the csv files and merge them into one csv file
import os
import pandas as pd
import numpy as np
import glob
import sys
import argparse
import re
#get the arguments
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--directory', help='directory where the csv files are', ... |
import numpy as np
class GNaiveBayes:
"""Clasificador Gaussian Naive Bayes.
Esta es una implementación del clasificador Gaussian Naive Bayes, basado en el teorma de Bayes
y asumiendo que los datos siguen una distribución normal Gaussiana. Para emplear este clase primero
se debe instanciar, entrenar c... |
class Solution:
def canCompleteCircuit(self, gas: list[int], cost: list[int]) -> int:
total, curr = 0, 0
start = 0
diff = 0
for i in range(len(gas)):
diff = gas[i] - cost[i]
total += diff
curr += diff
if curr < 0:
star... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Country',
fields=[
('id', models.AutoField(auto... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Ported from:
# https://github.com/adafruit/Adafruit_Python_SSD1306/blob/master/examples/shapes.py
import sys
import time
from PIL import Image, ImageDraw
from demo_opts import device
import demo
class Timer:
def __enter__(self):
self.start = time.clock()
... |
# -*- coding: utf-8 -*-
import os
import socket
from asyncy.Config import Config
from pytest import fixture
@fixture
def init(patch):
patch.object(Config, '__init__', return_value=None)
@fixture
def config():
return Config()
def test_config():
assert Config.defaults['LOGGER_NAME'] == 'asyncy'
as... |
# -*- coding: utf-8 -*-
"""
PLEASE DO NOT USE ME.
PLEASE DO NOT USE ME.
PLEASE DO NOT USE ME.
PLEASE DO NOT USE ME.
PLEASE DO NOT USE ME.
PLEASE DO NOT USE ME.
PLEASE DO NOT USE ME.
The functions in this namespace are provided for migrating sessions only.
The legacy system has security issues.
The following functio... |
# Removes redundancy from models that use other models as an input
import pickle
import numpy as np
from rdkit import Chem
from rdkit.Chem import rdMolDescriptors, Descriptors, MACCSkeys
from rdkit.Avalon.pyAvalonTools import GetAvalonFP
from functions import pka_similarities, logs_to_mg_ml
# All models inherit this ... |
import numpy as np
from argparse import ArgumentParser
import os
import time
import torch
import torch.nn as nn
import torch.optim as optim
from itertools import count
from coleo import Argument, default
from milarun.lib import init_torch, coleo_main, iteration_wrapper, dataloop
def generate_wave_data(T, L, N):
x... |
'''
WordTokenizer
basic_tokenizer: only split words by space
customized_tokenizer: split words, can remove punctuation (initially True), can make normalization(initially False), can remove dust(intitially False)
SentenceTokenizer:
basic_tokenizer: only split by Bangla_fullstop
customized_tokenizer: spl... |
import cv2
import time
import numpy as np
import pandas as pd
import librosa
protoFile = "models/pose_deploy_linevec.prototxt"
weightsFile = "models/pose_iter_440000.caffemodel"
net = cv2.dnn.readNetFromCaffe(protoFile, weightsFile)
inWidth, inHeight, threshold = 256, 256, 0.3
POSE_PAIRS = [ [1,0],[1,2],[1,5],[2,3],[... |
import discord
from discord.ext import commands
import asyncio
from utils import permissions, database
from utils import databasewrapper as db
from tinydb import Query
Q = Query()
reactions = ['\U00000031\U000020e3', '\U00000032\U000020e3', '\U00000033\U000020e3', '\U00000034\U000020e3', '\U00000035\U000020e3']
valid... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 26 08:20:48 2019
@author: MAHDI
"""
import numpy as np
import matplotlib.pyplot as plt
def GetY(solution , xval):
Y=0.0
for i in range(len(solution)):
Y = Y+ xval**i * solution[i]
return Y
def DrawPolinomial(solution,mycolor,mylabel):
x= np.linspac... |
from django.shortcuts import render, get_list_or_404, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
import regex as re
import functools
import datetime
from itertools import chain, cycle
from .models import PatientDemographic, PatientYear, Note... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-10-13 09:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0006_textrating_date'),
]
operations = [
migrations.AddField(
... |
"""Celer algorithm to solve L1-type regularized problems."""
from .homotopy import celer_path
from .dropin_sklearn import (ElasticNet, ElasticNetCV,
GroupLasso, GroupLassoCV,
Lasso, LassoCV, LogisticRegression,
MultiTaskLasso, Multi... |
from numpy import *
from mkcgent2dgent import mkcgent2dgent
from createcgcells import createcgcells
from getcelltype import getcelltype
def createcggrid(dgnodes,tlocal):
# Get some dimensions of the mesh
nd = dgnodes.shape[1];
ne = dgnodes.shape[2];
nve = tlocal.shape[1];
cgelcon,tm1,tm2,tm3,cgno... |
#!/usr/bin/env python3
"""
This script allows you to manually control the simulator
using the keyboard arrows.
"""
import sys
import argparse
import pyglet
import math
from pyglet.window import key
from pyglet import clock
import numpy as np
import gym
import gym_miniworld
from gym_miniworld.params import *
parser = ... |
import numpy as np
#
def sglscat(mu0, mu, az, tau0, ssa, xk):
'''
Purpose:
To compute single scattering approximation in homogeneous atmosphere
In:
mu0 d cos(sza) > 0, sza=[0, 90)
mu d[nmu] -cos(vza); mu = [mu_toa < 0, mu_boa > 0], mu_toa, if any, must come first
... |
path = list()
circd = dict()
def set_path(pathlist):
path.clear()
for d in pathlist:
path_add(d)
def path_add(d):
if not d in path:
path.append(d)
def path_del(d):
if d in path:
path.remove(d)
|
from __future__ import annotations
from decimal import Decimal
from typing import Tuple, Callable, Union, Iterable, Dict, Optional
import f
from f.grammar import FLarkTransformer
class Frame:
def __init__(self, parent: Optional[Frame]):
self.parent = parent
self.variables: Dict[str, Value] = {}
... |
import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-markdownify',
version='0.9.0',
packages=['markdowni... |
from .config import RecconEmotionEntailmentConfig
from .tokenization import RecconEmotionEntailmentTokenizer
from .modeling import RecconEmotionEntailmentModel
from .preprocess import RecconEmotionEntailmentPreprocessor
from .postprocess import RecconEmotionEntailmentPostprocessor
from .train import train_model
from .e... |
example_grid = [
[5,0,0,0,0,7,0,0,0]
,[9,2,6,5,0,0,0,0,0]
,[3,0,0,8,0,9,0,2,0]
,[4,0,0,0,2,0,0,3,5]
,[0,3,5,1,0,4,9,7,0]
,[8,6,0,0,5,0,0,0,4]
,[0,4,0,3,0,8,0,0,2]
,[0,0,0,0,0,5,6,9,3]
,[0,0,0,6,0,0,0,0,7]]
def print_grid(grid):
for row in g... |
import torch.utils.data as data
import random
from PIL import ImageFile
from dataset.augmentation import SSJAugmentation
from dataset.Parsers.MOT17 import GTParser_MOT_17
ImageFile.LOAD_TRUNCATED_IMAGES = True
class MOT17TrainDataset(data.Dataset):
'''
The class is the dataset for train, which read gt.txt fi... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import os
import re
import sys
import git ## pip install gitpython
import xlwt ## pip install xlwt
import getopt
### CRR Project
CRS_GIT = "https://github.com/coreruleset/coreruleset.git"
CRS_PATH=""
OUT_PATH=""
FILE_LIST = {
"SQLi" : "REQUEST-942-APPLICATION-... |
# -*- coding: utf-8 -*-
from amplify.agent.util import host
from amplify.agent.context import context
from amplify.agent.containers.abstract import AbstractObject
from amplify.agent.containers.system.collectors.meta.common import SystemCommonMetaCollector
from amplify.agent.containers.system.collectors.meta.centos impo... |
# Copyright 2015 Brocade Communications System, 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
#
#... |
#!/usr/bin/env python
#Copyright (C) 2009-2010 :
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
#
#This file is part of Shinken.
#
#Shinken is free software: you can redistribute it and/or modify
#it under the terms of the GNU Affero General P... |
#!/usr/bin/env python3
import signal
# Define signal handler function
def myHandler(signum, frame):
print('I received: ', signum)
# register signal.SIGTSTP's handler
signal.signal(signal.SIGTSTP, myHandler)
signal.pause()
print('End of Signal Demo')
|
#!Python3.8
# -*- coding: utf-8 -*-
import sys, os, time, subprocess, string
import numpy as np
import tqdm
from PIL import Image, ImageDraw, ImageFont
try:
import youtube_dl
import cv2
except Exception:
pass
class BasicImage:
"""BasicImage
Raises:
StopIteration: for i... |
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseBadRequest
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login
from .models import Mission, CompletedMission, MissionKey, User, Grade
from django.utils import timezo... |
class Solution(object):
def canPartitionKSubsets(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
s = sum(nums)
if s % k != 0:
return False
def test_can_partition_k_subsets():
s = Solution()
assert s.canPartitionKSu... |
# pylint: disable=C,R,E1101
import torch
import h5py
import numpy as np
import numbers
import sys
miccai_filters = {
'train': ["1000_3",
"1001_3",
"1002_3",
"1006_3",
"1007_3",
"1008_3",
"1009_3",
"1010_3",
... |
import tensorflow as tf
import datetime
print("Hello World")
|
def main():
input_file = open('input', 'r')
for line in input_file:
test_file = open('input', 'r')
for test_line in test_file:
matching_char = ''
for i, char in enumerate(line):
if (char == test_line[i]):
matching_char += char
... |
# Copyright 2020 Michael Still
import click
import datetime
import json
import logging
import sys
from shakenfist_client import apiclient
from shakenfist_client.commandline import admin
from shakenfist_client.commandline import artifact
from shakenfist_client.commandline import instance
from shakenfist_client.command... |
# coding: utf-8
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic
from djutils.views.generic import TitleMixin
from .. import models
from .. import forms
from .. import consts
from ..generic import ReadAccessMixin, ModifyAccessMixin, FuncAccessMixin
class Create(TitleMixin, Fu... |
"""The function max() from exercise 1) and the function
max_of_three() from exercise 2) will only work for two
and three numbers, respectively. But suppose we have a
much larger number of numbers, or suppose we cannot tell
in advance how many they are? Write a function max_in_list()
that takes a list of numbers an... |
import collections
import logging
from typing import Any, AsyncIterator, DefaultDict, NamedTuple, Optional, Set, Type
from async_generator import asynccontextmanager
from eth_typing import NodeID
import trio
from ddht.abc import SubscriptionManagerAPI
from ddht.base_message import AnyInboundMessage, InboundMessage, T... |
import numpy as np
def latticeforest_image(state, position, image_dims):
"""
helper function to create an image of the forest.
Inputs:
- state: 2D numpy array containing full state of forest
- position: numpy array of (row, col) position of where to take image
- image_dims: output size (heigh... |
# coding=utf-8
# Copyright 2019 The Google Research Authors.
#
# 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 applicab... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 1 2020
yt_copyright_scraper.py
YouTube content id claims populate information in the video's description.
This script pulls that info from the first song claimed in a YouTube video.
Run this with a list of YouTube urls named "youtube_urls.txt" in th... |
import sys
import os
import click
import pathlib
import importlib
os.environ['FOR_DISABLE_CONSOLE_CTRL_HANDLER'] = 'T'
CONTEXT_SETTINGS = {'default_map': {'run': {}}}
class VnCliRun(click.MultiCommand):
def __init__(self, *args, **kwargs):
super(VnCliRun, self).__init__(*args, **kwargs)
self._ap... |
import sys
import time
from azure.storage import BlobService
from azure import WindowsAzureMissingResourceError
from CREDENTIALS import account_name, account_key
db = BlobService(account_name=account_name, account_key=account_key)
###
bucket = 'crawl-data'
in_progress = set()
#
existing = set([x.name for x in db.list... |
#!/usr/bin/python
from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
user_agent = db.Column(db.String(255))
created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
def __init__(self, email, user_agen... |
#
# Copyright (c) 2018 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
with open("inp7.txt") as file:
crabs = [int(n) for n in file.read().split(",")]
fuel1 = float("inf")
fuel2 = float("inf")
for pos in range(min(crabs), max(crabs) + 1):
f1, f2 = 0, 0
for crab in crabs:
steps = abs(pos - crab)
f1 += steps
f2 += steps * (1 + steps) // 2
fuel1 = m... |
"""
ImageResolver
Copyright 2020 Constituent Voice LLC
http://constituentvoice.com/
http://github.com/constituentvoice
ImageResolver is a port of the excellent ImageResolver
javascript library by Maurice Svay
https://github.com/mauricesvay/ImageResolver
"""
from imageresolver.base import FileExtensionResolver, ImageR... |
import cv2
from numpy import *
import os
import operator
def main():
if os.path.exists('labels.npy') & os.path.exists('trainingMat.npy'):
labels = load('labels.npy')
trainingMat = load('trainingMat.npy')
print(labels)
print(trainingMat)
else:
labels, trainingMat = creat... |
# Copyright 2020 Thomas Rogers
# SPDX-License-Identifier: Apache-2.0
import typing
import uuid
from direct.task import Task
from panda3d import core
from . import constants
class Clicker:
ALL_MOUSE_BUTTONS = {
core.MouseButton.one(),
core.MouseButton.two(),
core.MouseButton.three(),
... |
# This file is created by generate_build_files.py. Do not edit manually.
test_support_sources = [
"src/crypto/aes/internal.h",
"src/crypto/asn1/asn1_locl.h",
"src/crypto/bio/internal.h",
"src/crypto/bn/internal.h",
"src/crypto/bn/rsaz_exp.h",
"src/crypto/bytestring/internal.h",
"src/crypto/... |
# Copyright 2020 Google LLC
#
# 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, ... |
from __future__ import print_function
import os
from concurrent.futures import ProcessPoolExecutor
from subprocess import call
from simpleference.inference.util import get_offset_lists
import z5py
def single_inference(sample, gpu, iteration):
call(['./run_inference.sh', sample, str(gpu), str(iteration)])
ret... |
import time
import torch
from progress.bar import Bar
from torch import optim
from torch.utils.data import DataLoader
from dlmcol.InvariantColorNNet import InvariantColorNNet
class AverageMeter:
"""Computes and stores the average and current value
Imported from https://github.com/pytorch/examples/blob/maste... |
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.urlresolvers import reverse
from django.test import TestCase
from bento.models import TextBox, ImageBox
IMPORT_JSON_DATA = """
[
{
"pk": 1,
"model": "bento.te... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2021 Cloudera, 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/LIC... |
def check_prime(number):
for divisor in range(2, int(number ** 0.5) + 1):
if number % divisor == 0:
return False
return True
def Primes(max_):
number = 1
generated = 0
while generated < max_:
number += 1
if check_prime(number):
generated += 1
... |
r"""Core class hierarchy for Hilbert spaces
This module defines some simple classes to describe simple and
*composite/tensor* (i.e., multiple degree of freedom)
Hilbert spaces of quantum systems.
For more details see :ref:`hilbert_space_algebra`.
"""
import functools
import operator
import re
from abc import ABCMeta,... |
#!/usr/bin/env python3
import sys
import getopt
import traceback
import _server
DEFAULT_PORT = 1337
DEFAULT_PLAYERS = 4
DEFAULT_PASSWORD = None
LADDR = '0.0.0.0'
def eprint(*argv):
print(*argv, file=sys.stderr)
usage = (
"usage: server [options]\n"
"\n"
" -h --help :: this\n"
f" -p... |
class colors:
header = '\033[95m'
blue = '\033[94m'
green = '\033[92m'
alert = '\033[93m'
fail = '\033[91m'
normal = '\033[0m'
bold = '\033[1m'
underline = '\033[4m' |
from __future__ import absolute_import
import json
from gevent import sleep
from kazoo.exceptions import NodeExistsError
from pytest import fixture, mark
from huskar_api.models import huskar_client
from huskar_api.models.container import ContainerManagement
from huskar_api.models.instance.schema import Instance
from... |
"""
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol I V X L C D M
Value 1 5 10 50 100 500 1000
For example, two is written as II in Roman numerals, just two one's added together. Twelve is written as, XII,
which is simply X + II. The number twenty... |
#!/usr/bin/env
# -*- coding: utf-8 -*-
# Copyright (C) Victor M. Mendiola Lau - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Written by Victor M. Mendiola Lau <ryuzakyl@gmail.com>, August 2016
import numpy as np
import measures
def bu... |
pose_sub = rospy.Subscriber('/turtle1/pose', Pose, poseCallback)
|
import boto3
from dagster import check
MAX_KEYS = 1000
def get_s3_keys(bucket, prefix="", since_key=None, s3_session=None):
check.str_param(bucket, "bucket")
check.str_param(prefix, "prefix")
check.opt_str_param(since_key, "since_key")
if not s3_session:
s3_session = boto3.resource("s3", use... |
import sys
sys.path.insert(0, './solax')
import solax
import asyncio
import json
import os
from solax import inverter
from http.server import HTTPServer, BaseHTTPRequestHandler
async def LoadSolaxData():
# r = await solax.real_time_api(os.environ['SOLAX_IP'],80,'admin')
r = solax.RealTimeAPI(i... |
# -*- coding: utf-8 -*-
"""Tests for `.tileconfig` module."""
import os
import pytest
import yaml
from tile_processor import tileconfig, db
@pytest.fixture(scope="function")
def polygons(data_dir):
yield {
"file": os.path.join(data_dir, "extent_small.geojson"),
"ewkb": "01030000204071000001000... |
def crawl_web(seed):
tocrawl = [seed]
crawled = []
index = []
while tocrawl:
pagelink = tocrawl.pop()
if pagelink not in crawled:
content = get_page(pagelink)
add_page_to_index(index, pagelink, content)
union(tocrawl, get_all_links(content))
... |
# wkhtmltopdf is required (install through apt)
import requests
import os
import os.path
import pdfkit
SECTIONS_URL = "https://foxford.ru/wiki/api/sections?discipline_id=6&grade_id=6"
THEME_URL_TEMPLATE = "https://foxford.ru/wiki/obschestvoznanie/{translit_name}"
def main():
""" Used to download books from foxford ... |
from typing import Tuple, ClassVar, List
import logging
import os
import numpy as np
import pandas as pd
try:
from ipyleaflet import Map, Marker, MarkerCluster, Polyline
import webbrowser
except ImportError:
logging.error("Import of ipyleaflet or webbrowser failed.")
try:
import plotly.graph_objects ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.