content stringlengths 5 1.05M |
|---|
import os
import time
import webbrowser
print("Beginning set-up")
os.system("pip3 install -r requirements.txt")
print("Step1-> setting clustername")
os.system("python3 settings.py")
print("Step2-> adding the git repository")
os.system("git add .")
print("Step 3->commit and pushing to hasura cluster")
os.system("git co... |
from torchvision import models, transforms
from torchvision.datasets import ImageFolder
from medcam import medcam
import torch
import cv2
from torch.utils.data import DataLoader
import gc
import shutil
import os
import unittest
CLEAR = True
class TestClassification(unittest.TestCase):
def __init__(self, *args, ... |
import phonenumbers
from phonenumbers import carrier, geocoder
from termcolor import colored
import auxillary
class Local:
# initializes the instance attributes
def __init__(self, phone_no) -> None:
self.phone_no = phone_no
self.parse_details = phonenumbers.parse(self.phone_no)
self.n... |
from collections import deque
import torch
torch.backends.cudnn.benchmark = True
import torch.nn.functional as F
import numpy as np
from core.network import Network
from core.optimizer import Optimizer
from core.buffer import PERBuffer
from .rainbow import Rainbow
class RainbowIQN(Rainbow):
"""Rainbow IQN agent... |
import cirq
import kc_examples.kc_bell_inequality
import kc_examples.kc_bernstein_vazirani
import kc_examples.kc_grover
# import examples.place_on_bristlecone
# import kc_examples.kc_hello_qubit
import kc_examples.kc_quantum_fourier_transform
# import examples.bcs_mean_field
import kc_examples.kc_phase_estimator
import... |
import os
import sys
from urllib.parse import urlparse
import click
import filelock
import structlog
from eth_utils import encode_hex, to_canonical_address, to_checksum_address, to_normalized_address
from requests.exceptions import ConnectTimeout
from web3 import HTTPProvider, Web3
from raiden.constants import SQLITE... |
from .mapper import ApiResponse, ApiResponseInterface
from .mapper.types import Timestamp, AnyType
__all__ = ['DirectRecentRecipientsResponse']
class DirectRecentRecipientsResponseInterface(ApiResponseInterface):
expiration_interval: AnyType
recent_recipients: AnyType
class DirectRecentRecipientsResponse(A... |
token = ...
welcome_channel_id = ...
birthday_channel_id = ...
|
from parasolr.django import AliasedSolrQuerySet
class WorkSolrQuerySet(AliasedSolrQuerySet):
"""':class:`~parasolr.django.AliasedSolrQuerySet` for
:class:`~mep.book.models.Item`"""
#: always filter to item records
filter_qs = ['item_type:work']
#: map readable field names to actual solr fields
... |
"""Test add node to graph."""
import pytest
import vt_graph_api
import vt_graph_api.errors
test_graph = vt_graph_api.VTGraph(
"Dummy api key", verbose=False, private=False, name="Graph test",
user_editors=["agfernandez"], group_viewers=["virustotal"])
def test_add_link(mocker):
"""Test add link."""
mo... |
# -*- coding: utf-8 -*-
import sys
sys.path.append('.')
from common import TestCase
import unittest
import fatuv as uv
import tempfile
import os
U_TIME = (4200, 4200)
class TestFSPoll(TestCase):
def test_fs_poll_change(self):
def on_change(fs_poll, status, previous_stat, current_stat):
#self.assert_not_equal(... |
class InputStream:
"""
Stream that bring new data to the system,
Like user keyboard or socket info.
To mark stream as input just inherit from InputStream in addition to the BasicStream
"""
pass
|
from django.contrib import admin
# Register your models here.
from .models import Cart
admin.site.register(Cart)
|
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
class Database():
def __init__(self, uri=None):
self.base = declarative_base()
self.session = None
if uri is not None:
self.set... |
from . import plot
from . import fit
from . import parfit
from . import score
from . import crossval
__all__ = (plot.__all__ + fit.__all__ + score.__all__ + crossval.__all__ + parfit.__all__)
|
import os
import glob
import numpy as np
import pandas as pd
from skimage import io
import torch
from torch.utils.data import Dataset
import zipfile
from util import utils_np
'''
'''
class ImageStackDatasetSim(Dataset):
def __init__(self, csv_path, root_dir, channel_per_image, transform=None, T_channel=False):... |
# environment variables
ATOM_PROGRAM = '/home/physics/bin/atm'
ATOM_UTILS_DIR ='/home/physics/bin/pseudo'
element = "Fe"
equil_volume = 11.3436
# general calculation parameters
calc = {"element": element,
"lattice": "BCC",
"xc": "pb",
"n_core": 5,
"n_val": 2,
"is_spin_pol": Tr... |
#!/usr/bin/env python3
# how to pickle data
import os
import pickle
a = b'12345678'
b = b'9abcdef'
print('a = {}; b = {}'.format(a,b))
# write data to file
cwd = os.getcwd()
file_name = os.path.join(cwd,'program_state.bin')
with open(file_name,'wb+') as f:
pickle.dump(a,f)
pickle.dump(b,f)
a = b'9abcdef'
b =... |
"""
Created on Sep 14, 2015
@author: Mikhail
"""
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.expected_conditions import *
# Project's imports
from mera.selenium_training_automation.pages.page import Page
__author__ = 'Mikhail'
class HomePage(Page):
... |
import bpy
class GESIO_OT_Paths(bpy.types.PropertyGroup):
footage_path: bpy.props.StringProperty(name="footage_000",
subtype='FILE_PATH',
default=r"")
json_path: bpy.props.StringProperty(name="JSON",
... |
def flatten_struct(df):
struct_cols = [name for name, dtype in df.dtypes if 'struct' in dtype]
if struct_cols:
col_to_flatten=[{'from':f'{nc}.{c}','to':f'{nc}_{c}'} for nc in struct_cols for c in df.select(f'{nc}.*').columns]
for col in col_to_flatten:
df = df.withColumn(col['to'],F.... |
from django.db import models
from datetime import datetime
from users.models import UserProfile
# Create your models here.
class Projects(models.Model):
PROJECT_FIELD = (
('1', "金融产品"),
('2', "电信产品"),
('3', "物联网相关"),
)
PROJECT_STATUS = (
('1', "立项阶段"),
('2', "开发阶段... |
import pygame
from Bullet import Pocisk
from Alien import Alien
from kropla import drop
from Boss import boss
from BulletBoss import PociskBoss
from time import sleep
from ExtraBullet import BulletPlus
from Animations import Explosion
clock = pygame.time.Clock()
pygame.init()
pygame.mixer.pre_init(44100, -16, 2, 512)
i... |
import torch
import math
import numpy as np
from utils import LeastSquares
def split_coeff(coeff):
# input: coeff with shape [1,257]
id_coeff = coeff[:, :80] # identity(shape) coeff of dim 80
ex_coeff = coeff[:, 80:144] # expression coeff of dim 64
tex_coeff = coeff[:, 144:224] # texture(albedo) co... |
import logger
import time
import unittest
import threading
from threading import Thread
from membase.helper.rebalance_helper import RebalanceHelper
from couchbase_helper.cluster import Cluster
from basetestcase import BaseTestCase
from remote.remote_util import RemoteMachineShellConnection
import json
import sys
from ... |
from random import randint
class Dice():
"""A class that represents a unique dice"""
def __init__(self, num_sides=6):
"""Assumes the dice has 6 sides"""
self.num_sides = num_sides
def roll(self):
"""Returns a random value between 1 and the number of sides"""
return randin... |
# 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 a... |
"""
Wrapper around the standard logging module to provide a simpler initiation and
consistent formatting.
The differences from the standard are;
- we always log to file
- we use a standardised format
- our default logging level is INFO, not WARN
- the formatter does not include the log name ... |
import socket
import re
import multiprocessing
import sys
# import dynamic.mini_frame
class WSGIServer(object):
def __init__(self, ip, port, application, static_path):
# 1. 创建套接字
self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.tcp_server_socket.setsockopt(so... |
from flask import Flask
from flask import jsonify, render_template, make_response
from utils import test_user_input, add_result
from config import CACHE
app = Flask(__name__)
# рендерит стартовую страницу
@app.route('/', methods=['GET'])
def main():
return render_template('index.html'), 200
# результат запро... |
# -*- coding: utf-8 -*-
""" Module to implement acoustic shadowing along with spherical spreading
of sound
Created on Mon Jun 17 16:08:50 2019
@author: tbeleyur
"""
import time
import sys
sys.path.append('..//bridson//')
sys.path.append('..//')
import numpy as np
import pandas as pd
import scipy.spatial as spatial
... |
class Debug:
def __init__(self):
self.DEBUG=False
def Set(self):
self.DEBUG=True
def Unset(self):
self.DEBUG=False
def __call__(self):
return self.DEBUG
DEBUG=Debug()
DEBUG.Set()
DEBUG.Unset() |
#!/usr/bin/env python
__author__ = 'Leland Taylor'
__date__ = '2020-03-13'
__version__ = '0.0.1'
import argparse
import os
import pandas as pd
def main():
"""Run CLI."""
parser = argparse.ArgumentParser(
description="""
Filter and merge 10x data. Save to AnnData object.
"""
... |
import json
import logging
import multiprocessing as mp
import pickle
import time
from collections import Counter
from copy import deepcopy
from typing import List, Union, Tuple
import numpy as np
from flare.env import AtomicEnvironment
from flare.gp_algebra import (
get_like_from_mats,
get_neg_like_grad,
... |
import unittest
from import_new_tournaments.process_hh_files.process.hands.extract.main_pot_winner import main_pot_winner
from GLOBAL_VARIABLES import TEST_RANDOM_HAND_HISTORIES_FOLDER
from import_new_tournaments.process_hh_files.process.tournament.extract.hands import get_hands_in_list
class test(unittest.TestCase):... |
import os
from setuptools import find_packages, setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
# This call to setup() does all the work
setup(
name="pypokemontcg",
version="0.0.0",
description="SDK for pokemontcg APIs",
long_description=read('README.md'),... |
# Copyright (C) 2021-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
"""This module define the scored label entity."""
import datetime
from ote_sdk.entities.color import Color
from ote_sdk.entities.id import ID
from ote_sdk.entities.label import Domain, LabelEntity
class ScoredLabel:
"""
Thi... |
import asyncio
from functools import partial
from typing import Any
import aiohttp
from python_keycloak_client.aio.abc import AsyncInit
from python_keycloak_client.client import KeycloakClient as SyncKeycloakClient
from python_keycloak_client.exceptions import KeycloakClientError
__all__ = (
'KeycloakClient',
)
... |
import os
import sys
DATA_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.abspath(os.path.dirname(DATA_DIR)))
from selenium import webdriver
from Screenshot import Screenshot_Clipping
chromedriver_path = os.path.abspath(DATA_DIR + '/chromedriver.exe')
def test_full_screenshot():
ob ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-02-19 20:56:46
# @Author : ZubinGou (zebgou@gmail.com)
# @Link : https://github.com/ZubinGou
# @Version : $Id$
from __future__ import print_function
import tensorflow as tf
hello = tf.constant("Heyyyy, TensorFlow!")
print(hello)
|
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context("paper", rc={'font.sans-serif': 'Helvetica',
'font.size': 12})
df_green = pd.read_csv('~/Resources/Experiments/dcfnex-12/dcstfn-green/train/history.csv')
df_red = pd.read_csv('~/Resources/Experiments... |
import numpy
import os
def get_minimums_and_risks(height_map):
mins_ind = []
risk_level = 0
len_x = len(height_map[0])
len_y = len(height_map)
# go over y
for y in range(0, len_y):
# go over x
for x in range(0, len_x):
neighb_indexs = get_neighb_indexs(x, y, len_x -... |
from functools import lru_cache
from django.apps import apps
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from menus.menu_pool import menu_pool
def get_admin_name(model, name):
name = '{}_{}_{}'.format(
model._meta.app_label,
model._meta.model_name,
... |
import numpy as np
def apply_threshold(output, speech_threshold=0.5, music_threshold=0.5):
output[0] = np.where(output[0] >= speech_threshold, 1, 0)
output[1] = np.where(output[1] >= music_threshold, 1, 0)
return output.astype(int)
|
from stationdata import build_station_list, update_water_levels
from utils import sorted_by_key
def stations_level_over_threshold(stations,tol):
list_of_tup = []
for station in stations:
if station.typical_range_consistent() == True:
if station.latest_level != None and station.relative_... |
from django.test import TestCase
import json
from app.tests.test_modules.loader import test_flow, TestCaseFlow, TestCaseFlowRunner
from module.MicrocloudchipException.base_exception import MicrocloudchipException
from module.data.user_data import UserData
from app.tests.test_modules.testing_user_module import *
cla... |
n = int(input())
temp = list(map(int, input().split()))
maxx = temp[0]
minn = temp[0]
for i in range(n):
if maxx<=temp[i]:
maxx = temp[i]
for i in range(n):
if minn>=temp[i]:
minn = temp[i]
print(maxx, minn)
|
# -*- coding: utf-8 -*-
COUNTRIES_LIST = [(u'Afghanistan', u'AF', u'AFG', 4, u'ISO 3166-2:AF'),
(u'\xc5land Islands', u'AX', u'ALA', 248, u'ISO 3166-2:AX'),
(u'Albania', u'AL', u'ALB', 8, u'ISO 3166-2:AL'),
(u'Algeria', u'DZ', u'DZA', 12, u'ISO 3166-2:DZ'),
(u'American Samoa', u'AS', u'ASM', 16, u'ISO 3166-2:AS'),... |
from django.urls import path
from django.conf.urls import url
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('contact/', views.contact, name='contact'),
path('submit/', views.submit, name='submit'),
path('studentmanager/', views.studentmanager, name='studentmanager'),
... |
import json
def convert_sudoku(sudoku):
output = {i: "" for i in range(9)}
string_output = {i: "" for i in range(9)}
sudoku_row = [str(-1) for i in range(9)]
sudoku_mat = [sudoku_row.copy() for i in range(9)]
grid = 0
for item in sudoku["puzzle"]:
if int(item[0]) == grid:
... |
from src.genotype.neat.operators.mutators.mutation_report import MutationReport
class Mutagen:
"""This is the base class for any mutate-able property"""
def __init__(self, name: str, mutation_chance: float):
self.name = name
self.mutation_chance = mutation_chance
def __repr__(self):
... |
# -*- coding: utf-8 -*-
import ctypes
import time
from ctypes import c_short, c_char, c_uint8, c_int32, c_int, c_uint, c_uint32, c_long, byref, Structure, CFUNCTYPE, POINTER
from ctypes.wintypes import DWORD, BOOL, HHOOK, MSG, LPWSTR, WCHAR, WPARAM, LPARAM
LPMSG = POINTER(MSG)
import atexit
from ._mouse_even... |
from typing import List
from collections import Counter
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
paragraph = list(paragraph)
# print(paragraph)
for k in range(len(paragraph)):
if not (65<=ord(paragraph[k])<=90 or 97<=ord(paragraph[k])<=... |
import torch
from torch.distributions import Bernoulli
from torch.distributions.continuous_bernoulli import ContinuousBernoulli
from distributions.conditional import ConditionalDistribution
from utils import sum_except_batch
class ConditionalBernoulli(ConditionalDistribution):
"""A Bernoulli distribution with co... |
"""
Read namelists
"""
from f90nml import Namelist, Parser
import multiprocessing as mp
import re
from typing import List, Union, Tuple
_nml_types = Union[int, float, bool, str]
_array_rg = re.compile(
"((?:[a-z][a-z0-9_]*))(\\()(\\d+)(\\))(.*)", re.IGNORECASE | re.DOTALL
)
######################################... |
# Copyright 2021 The ParallelAccel Authors. 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 appl... |
from flask_pymongo import PyMongo
from flask import Flask, flash, render_template, redirect, request, url_for, \
session, flash, Markup
from bson.objectid import ObjectId
from werkzeug.security import generate_password_hash, check_password_hash
import os
from os import path
if path.exists("env.py"):
imp... |
#Done by Lauro Ribeiro (12/02/2021)
# Tutorial 11 - AND/OR
import sqlite3
#Connect the database
conn = sqlite3.connect('customer.db')
#Create a cursor
c = conn.cursor()
#Query the database - AND/OR
c.execute("SELECT rowid, * FROM customers WHERE last_name LIKE '%Ribeiro' \
AND email LIKE '%gmail.com'... |
<info descr="null">async</info> def <info descr="null">foo</info>():
<info descr="null">await</info> x
await = 0
|
from random import shuffle
import numpy as np
import torch
import torch.nn as nn
import math
import torch.nn.functional as F
from PIL import Image
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torch.utils.data.dataset import Dataset
from utils.utils import bbox_iou, merge_bboxes
from ... |
"""
This example runs a dummy 1D bayesian optimization.
1. set up data
2. Then file runs the run_one_1d_bayesian_optimization function.
The function returns a grid of predicted mean/variance/etc.
3. Finally step plots the predicted mean & variance.
"""
from src.bayesian import run_one_1d_bayesian_optimization
imp... |
"""
Code to develop and test the sinking algorithm.
"""
import numpy as np
import matplotlib.pyplot as plt
# z-coordinates (bottom to top, positive up)
H = 50 # max depth [m]
N = 25 # number of vertical grid cells
C = np.exp(-np.linspace(-2,2,N)**2)
Wsink = .1#80 # m per day
dt = .1 # time step in days
Dz = H/N
z_w =... |
import os
from django.forms.fields import FileField
from crispy_forms.layout import HTML
from django_modals.modal_upload import ModalAjaxFileMixin
from django_modals.forms import CrispyForm
from django_modals.modals import FormModal
from django_modals.helper import progress_bar
from .views import MainMenuTemplateView... |
import numpy as np
def draw_line(xyz1, xyz2, num=1000):
x1 = xyz1[0]
x2 = xyz2[0]
y1 = xyz1[1]
y2 = xyz2[1]
z1 = xyz1[2]
z2 = xyz2[2]
x_line = np.linspace(x1, x2, num).reshape([-1, 1])
y_line = np.linspace(y1, y2, num).reshape([-1, 1])
z_line = np.linspace(z1, z2, num).reshape([-... |
pessoas_maiores_idade = 0
homens = 0
mulheres_menos_20_anos = 0
while True:
print('-' * 30)
print('{:^30}'.format('CADASTRE UMA PESSOA'))
print('-' * 30)
idade = int(input('Idade: '))
if idade > 18:
pessoas_maiores_idade += 1
sexo = ""
while sexo != 'M' and sexo != 'F':
se... |
from .internal import NeighborDistanceNormalization
import flowws
from flowws import Argument as Arg
from geometric_algebra_attention import keras as gala
from tensorflow import keras
import numpy as np
import tensorflow as tf
NORMALIZATION_LAYERS = {
None: lambda _: [],
'none': lambda _: [],
'batch': lam... |
from dataloader.DataloaderApi import *
import torch.nn as nn
import torch.optim
import time
import difflib
import torch.nn.functional as F
import datetime
from collections import Counter
from GPT.RAdam.radam.radam import RAdam
from math import log
from numpy import array
from numpy import argmax
from colle... |
from abc import ABC, abstractmethod
from pathlib import Path
from typing import List
from virtool_workflow.data_model import HMM
class AbstractHMMsProvider(ABC):
path: Path
@abstractmethod
async def get(self, hmm_id: str):
"""Get the HMM annotation with the given ID."""
...
@abstrac... |
import datetime
import os
from tempfile import TemporaryFile
import webbrowser
from django.core.files.temp import gettempdir
from django.core.management.base import BaseCommand, CommandError
from canvas.models import Comment
from django.conf import settings
class Command(BaseCommand):
args = 'filename'
help... |
from __future__ import print_function
import argparse
import random
import numpy as np
import time
import math
from collections import OrderedDict, defaultdict
from pybullet_tools.utils import load_model, TURTLEBOT_URDF, joints_from_names, \
set_joint_positions, HideOutput, get_bodies, sample_placement, pairwise_... |
from __future__ import print_function
from cloudmesh.config.cm_config import cm_config
from cloudmesh.shell.cm_cloud import CloudManage
from cloudmesh_base.logger import LOGGER
from tabulate import tabulate
from cmd3.console import Console
from cloudmesh.shell.cm_cloud import shell_command_cloud
from docopt import doco... |
from django.contrib.gis.db import models
class Venue(models.Model):
"""
Model for a venue
"""
name = models.CharField(max_length=200)
location = models.PointField()
def __str__(self):
return self.name
class Event(models.Model):
"""
Model for an event
"""
name = models... |
import os
import csv
from math import ceil, floor
import gffutils
EXIT_GFF_REANNOTATION_ERROR = 3
try:
from Corekaburra.correct_gffs import annotate_refound_genes
except ModuleNotFoundError:
from correct_gffs import annotate_refound_genes
try:
from Corekaburra.exit_with_error import exit_with_error
except... |
import pretty_midi
import IPython.display
import math
import matplotlib.pyplot as plt
def make_music_heterophonic(pitches=60, durs=0.25, pgm=1, is_drum=False, format='inbrowser', sr=16000):
"""Turn a list of a list of numbers into music."""
# check and convert to list if needed
pitches = pitches if isins... |
# Generated by Django 3.0.4 on 2020-05-12 21:52
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('app', '0002_auto_20200513_0257'),
]
operations =... |
# Copyright (C) 2020-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from .pattern_utils import check_fused_scale_shift_patterns, get_fused_scale_shift_patterns, \
check_fused_op_const_patterns, get_fused_op_const_pattern, get_clamp_mult_const_pattern
def get_gpu_ignored_patterns():
return {
... |
"""Leetcode 1161. Maximum Level Sum of a Binary Tree
Medium
URL: https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/
Given the root of a binary tree, the level of its root is 1,
the level of its children is 2, and so on.
Return the smallest level X such that the sum of all the values of nodes
at level... |
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.operators.python_operator import ShortCircuitOperator
from airflow.operators.python_operator import BranchPythonOperator
from datetime import datetime, timedelta
import pandas as pd
from sklearn import datasets
import os
... |
# -*- coding: utf-8 -*-
# --------------------------------------------------------
# RefineDet in PyTorch
# Written by Dongdong Wang
# Official and original Caffe implementation is at
# https://github.com/sfzhang15/RefineDet
# -------------------------------------------------------- |
import unittest
from source.code.MyDBCAN import MyDBCAN
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
class TestMyDBSCAN(unittest.TestCase):
def setUp(self):
# TODO: generate train/test data frames
self.my_dbscan = MyDBCAN()
def test_my_dbscan(self):
dbs... |
def sanitize(inputstr):
sanitized = inputstr
badstrings = [
';',
'$',
'&&',
'../',
'<',
'>',
'%3C',
'%3E',
'\'',
'--',
'1,2',
'\x00',
'`',
'(',
')',
'file://',
... |
#!/usr/bin/env python
import os
import math
import numpy as np
import cst.sord
# FIXME: prestress not correct
dx = 100.0
dt = dx / 12500.0
nx = 2
ny = int(16500.0 / dx + 21.5)
nz = int(12000.0 / dx + 120.5)
nt = int(8.0 / dt + 1.5)
alpha = math.sin(math.pi / 3.0)
prm = {
'affine': [
[1.0, 0.0, 0.0],
... |
#! /usr/bin/env python
# $Id: test_traversals.py 4641 2006-06-28 16:27:55Z blais $
# Author: Martin Blais <blais@furius.ca>
# Copyright: This module has been placed in the public domain.
"""
Test module for traversals.
"""
import unittest
import DocutilsTestSupport # must be imported before docutils
fro... |
'''
the model for learning the initial guess
'''
import os
from argparse import Namespace
import torch
from models import base_model, resnet
from utils import utils
class InitialGuesserFactory(object):
@staticmethod
def get_initial_guesser(opt):
if opt.guess_model == 'init_guess':
model... |
import unittest
from eth_utils import to_canonical_address
from raiden_installer import load_settings
from raiden_installer.tokens import (
Erc20Token,
EthereumAmount,
RequiredAmounts,
SwapAmounts,
TokenAmount,
TokenError,
Wei,
)
class TokenAmountTestCase(unittest.TestCase):
def setU... |
# -----------------------------------------------------------
# Copyright (c) 2021. Danil Smirnov
# Write a program that reads the names of the two primary
# colors for mixing. If the user enters anything other than
# red, blue, or yellow, the program should display an error
# message. Otherwise, the ... |
# Generated by Django 2.1.13 on 2021-01-18 14:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('trade', '0008_auto_20210118_2226'),
]
operations = [
migrations.AlterField(
model_name='resourcechange',
name='orde... |
import sqlite3
from Client import Client
class DBManager:
LOGIN_SQL = """
SELECT id, username, balance, message
FROM clients
WHERE username=? AND password=?
LIMIT 1 """
CHANGE_PASS_SQL = """
UPDATE clients
SET password=?
WHERE id=? """
UPDATE_MSG_SQL = """
UPDATE clients
... |
STRUCT_INIT_TIME = 4.6
ADD_FILE_TIME = 3.3
DEL_FILE_TIME = 1.5
UPD_FILE_TIME = 1.5
|
import operator
import argparse
import progressbar
import json
from spacy.en import English
parser = argparse.ArgumentParser()
parser.add_argument('-split', type=str, default='train',
help = 'Options are train, val, test, test-dev')
parser.add_argument('-answers', type=str, default='top1000',
... |
from typing import Dict
from typing import Optional
from ...ffprobe import FFprobe
from .audio_parameters import AudioParameters
from .input_audio_stream import InputAudioStream
from .input_stream import InputStream
from .input_video_stream import InputVideoStream
from .video_parameters import VideoParameters
from .vi... |
from abc import ABCMeta
from abc import abstractmethod
from ..np_utils import ops
import numpy as np
class Match(object):
"""Class to store results from the matcher.
This class is used to store the results from the matcher. It provides
convenient methods to query the matching results.
"""
def _... |
import numpy as np
import logging
from timeit import default_timer as timer
from sklearn.mixture import GMM
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
class Model:
def __init__(self):
self.__n_features = None
self.__n_clusters = None
self.__preproc... |
# -*- coding: utf-8 -*-
#
# clx.py - Ethernet/IP Client for Rockwell PLCs
#
#
# Copyright (c) 2014 Agostino Ruscito <ruscito@gmail.com>
#
# 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 witho... |
# Imports
import tests.utils as utils
import pytest
import os
@pytest.fixture(scope='session')
def create_intermediate_file(request):
# In case there is an intermediate file conversion needed (e.g. PSIM to XML)
# The approppriate function for the source_file_format will be called
source_file_format, path_a... |
# ------------------------------------------------------------------------------
# Copyright (c) 2019 Parallax Inc. -
# -
# Permission is hereby granted, free of charge, to any person obtaining ... |
from flask import Flask
app = Flask(__name__)
app.config.from_object("common.config.DevelopmentConfig")
from ewi.api import views
|
# -*- coding: utf-8 -*-
import json
import os.path
import yaml
from chaoslib.exceptions import ActivityFailed
from chaoslib.types import Secrets
from kubernetes import client
from kubernetes.client.rest import ApiException
from logzero import logger
from chaosk8s import create_k8s_api_client, add_trigger_environment_... |
# -*- coding: utf-8 -*-
import time
import datetime
from datetime import timedelta
import sys
import os
import re
import md5
from google.appengine.ext import ndb
import utils
from model.users import Users
from model.connections import Connections
from init import InitHandler
from model.devices import Devic... |
#! python
from airtable import Airtable
import discord, fstrings, re, random, os
from datetime import datetime
# datetime object containing current date and time
AIRTABLE_API_KEY = os.getenv('AIRTABLE_API_KEY') # stored in .env
AIRTABLE_BASE_KEY = os.getenv('AIRTABLE_BASE_KEY') # stored in .env
CAMPAIGN_NAME = os.g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.