content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
"""sequtilities.py
Author: Kimon Froussios
Date last revised: 17/02/2020
Library of utility functions relevant to sequencing tasks.
"""
import os, sys, argparse, re, csv
import pandas as pd
from collections import Counter
import Levenshtein as lev
import pysam
from Bio import SeqIO
import ... |
#!/usr/bin/env python
from parsers import FType
from helpers import *
# Strategy:
# 1. move parasite right after File Header
# 2. adjust IFD pointers
# 3. adjust StripOffsets values
BYTE = 1
ASCII = 2
SHORT = 3
LONG = 4
RATIONAL = 5
Lengths = {
BYTE :1,
ASCII :1,
SHORT :2,
LONG :4,
RATIONA... |
import pytest
from skysight import corners
import numpy as np
def test_machoCorners():
machoCorners = corners.load_machoCorners()
assert np.all(np.isclose(np.abs(machoCorners), 129 / 360., atol=1e-5))
def load_decamCorners():
decamCorners = corners.load_decamCorners()
assert len(decamCorners) == 60... |
from __future__ import print_function
from time import sleep
from tqdm import tqdm, trange
from multiprocessing import Pool, freeze_support, RLock
L = list(range(9))
def progresser(n):
interval = 0.001 / (len(L) - n + 2)
total = 5000
text = "#{}, est. {:<04.2}s".format(n, interval * total)
# NB: ens... |
"""
[2015-11-06] Challenge #239 [Hard] An Encoding of Threes
https://www.reddit.com/r/dailyprogrammer/comments/3rrtxh/20151106_challenge_239_hard_an_encoding_of_threes/
Are you ready to take the [Game of
Threes](https://www.reddit.com/r/dailyprogrammer/comments/3rhzdj/20151104_challenge_239_intermediate_a_zerosum/) t... |
import argparse
import yaml
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import scipy.stats
from tqdm import tqdm
from torch.utils.data import DataLoader
import random
import datasets
import models
import utils
import utils.few_shot as fs
from datasets.samplers import Categorie... |
import os
from itertools import izip_longest
class FileWriter(object):
def __init__(self, out_dir, package, entities):
self.out_dir = out_dir
self.package = package
self.entities = entities
def __call__(self, w, out_path):
out_path = os.path.join(self.out_dir, out_path)
... |
import json
def query_builder(query, operation_name=None, variables=None, input_data=None):
data = dict(
query=query, operation_name=operation_name
)
if variables:
data["variables"] = variables
if input_data:
if variables in data:
data["variables"]["input"] = input_... |
from unittest import TestCase
from maze.index_mapper import IndexMapper
class TestIndexMapper(TestCase):
def test_init(self):
atom_indices = [i for i in range(10, 20)]
index_mapper = IndexMapper(atom_indices)
with self.subTest(msg='test main index keys'):
self.assertCountEqual(i... |
from __future__ import print_function
from subprocess import call
import time
import re
import os
import codecs
from marmot.util.alignments import train_alignments
from marmot.util.force_align import Aligner
from marmot.representations.representation_generator import RepresentationGenerator
from marmot.experiment.imp... |
# Python - 3.6.0
unusual_five = lambda: 'abcdef'.index('f')
|
import time
from typing import Any, Dict, List
import invoke
import nanoid
from invoke import Responder
import docker
NAMESPACE = "nb"
SERVICES = {
"postgres": "postgres:14-alpine",
"redis": "redis:6-alpine",
}
ipam_pool = docker.types.IPAMPool(
subnet="124.42.0.0/16",
iprange="124.42.0.0/24",
... |
''' Main passive radar processing script '''
import numpy as np
import yaml
import h5py
import dask.array as da
from dask.diagnostics import ProgressBar
from passiveRadar.config_params import getConfigParams
from passiveRadar.signal_utils import offset_compensation, channel_preprocessing
from passiveRadar.clutter_rem... |
"""
Example script to show how to run an adaptive classifier.
Generate synthetic data sets with either normal distributions or Poisson
distributions (for scl and flda)
X = N samples by D features data matrix for source domain
y = N samples by 1 vector of labels in {1,...,K} for source domain
Z = M samples by ... |
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class tags(models.Model):
name = models.CharField(max_length=30)
pic = models.ImageField(upload_to='posts/')
def __str__(self):
return self.name
def save_tag(self):
self.save()
def d... |
from sympy.abc import x
from sympy import factor
result = factor(x**2 + 3*x)
print(result)
result1 = factor(x**2 - 9)
print(result1)
result2 = factor(x**2 - 4 * x + 4)
print(result2)
|
from __future__ import print_function
import numpy as np
import tensorflow as tf
from edward.stats import uniform
from scipy import stats
sess = tf.Session()
def uniform_entropy_vec(loc, scale):
"""Vectorized version of stats.uniform.entropy."""
if isinstance(loc, float) or isinstance(loc, int):
retu... |
try:
from django.conf.urls import url
except ImportError:
# django 4 and up
from django.urls import re_path as url
from treewidget.views import get_node, move_node
urlpatterns = [
url(r'get_node/$', get_node, name='treewidget.get_node'),
url(r'move_node/$', move_node, name='treewidget.move_node'),
... |
# -*- coding: utf-8 -*-
import numpy as np
from collections import OrderedDict
from scipy.stats import multivariate_normal
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def reshape(x,input_dim):
'''
Reshapes x into a matrix with input_dim columns
'''
x = np.array(x)
... |
from tkinter import *
from tkinter.filedialog import askopenfilename
def NewFile():
print("New File!")
def OpenFile():
name = askopenfilename()
print(name)
def About():
print("This is a simple example of a menu")
root = Tk()
menu = Menu(root)
##root.config(menu=menu)
root['menu'] = menu
filemenu = Men... |
import torch
import torch.nn as nn
import torch.nn.functional as func
from torchsupport.structured import structures as cs
from torchsupport.structured import scatter
class DeletionPool(nn.Module):
def __init__(self, size):
super(DeletionPool, self).__init__()
self.project = nn.Linear(size, 1)
def forwar... |
#!/usr/bin/env python3
###############################################################################
# $Id: gdal_zip.py 428d6fbc987332afb0ba6c7b6913390f7386e864 2020-01-17 22:19:28 +0100 Even Rouault $
#
# Project: GDAL samples
# Purpose: Create a zip file
# Author: Even Rouault <even dot rouault at spatialys ... |
if "bpy" in locals():
import importlib
importlib.reload(cell_main)
importlib.reload(crack_functions)
importlib.reload(material_functions)
importlib.reload(utilities)
else:
from .process import cell_main
from .process import crack_functions
from .process import material_functions
fr... |
import argparse
import logging
import sys
import time
import yaml
from . import deserializers
from . import inputters
from . import outputters
from .parser import parse_recipe
from . import processors
from . import serializers
from .task import Task
def _set_logger(debug=False):
logger = logging.getLogger(__nam... |
from flask import render_template_string, request
from flask_login import current_user
from app import app
from app.module.setting.model import SettingModel
from app.module.candidate.model import CandidateModel
from app.helper.utils import msg_out, DataModel
from app.helper.datetime import DateTime
from sqlalchemy impo... |
import time, os, json
from collections import Counter
from pprint import pprint
from tqdm import tqdm
import subprocess#, multiprocessing
from functools import partial
from p_tqdm import p_uimap
RATIO = 4
#SENTINEL = " Mw RZ TZ YZ"
MERGE_CNT = 700
CHAR_CNT = 128
WORKERS = 32
import sys, os
sys.path.append(os.path.dirn... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2017-05-24 07:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0040_homepage_show_sponsors_section'),
]
operations = [
migration... |
# Generated by Django 3.0.5 on 2020-04-21 07:36
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('basta', '0008_auto_20200421_0109'),
]
operations = [
... |
import os
import asyncworker
from aiohttp import web
from aiohttp.test_utils import TestServer, TestClient
from asynctest import TestCase
class BaseApiTestCase(TestCase):
async def aiohttp_client(self, app: asyncworker.App) -> TestClient:
routes = app.routes_registry.http_routes
http_app = web.Ap... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 11 10:48:48 2018
@author: rtake
"""
import matplotlib.pyplot as plt
import numpy as np
x1 = np.random.rand(100,1)
x1 = x1 * 4 -2
x2 = np.random.rand(100,1)
x2 = x2 * 4 -2
y = 3 * x1 - 2 * x2 +1
plt.subplot(1,2,1)
plt.scatter(x1, y, marker='+')
plt.xlabel('x1')
plt.yl... |
import ants
import antspyt1w
import antspynet
import pandas as pd
import numpy as np
fn = antspyt1w.get_data('PPMI-3803-20120814-MRI_T1-I340756', target_extension='.nii.gz' )
x = ants.image_read( fn )
imgbxt = antspyt1w.brain_extraction( x, method='v1' )
x = antspyt1w.preprocess_intensity( x, imgbxt )
#################... |
"""
Aggregation Utils
"""
import inspect
from typing import Any, Dict, Optional, Tuple
def gather_init_params(
obj: Any,
ignore: Optional[Tuple[str, ...]] = None,
) -> Dict[str, Any]:
"""Extract the parameters passed to an object's ``__init__()``.
Args:
obj (object):
ignore (tup... |
from django.db import migrations
def insert_notestatus(apps, schema_editor):
Notestatus = apps.get_model('dfirtrack_main', 'Notestatus')
initial_values = [
'10_draft',
'20_ready_for_review',
'30_review',
'40_final',
]
for name in initial_values:
Notestatus.obj... |
import csv
import pathlib
from collections.abc import Container
from datetime import datetime
from typing import Optional
from typing import Union
from myrtlespeech.run.callbacks.callback import Callback
class CSVLogger(Callback):
r"""Logs at the end of an epoch to the file at ``path`` in CSV format.
The fi... |
import os
import time
import signal
import multiprocessing
from Queue import Empty
from . import app_settings
from .utils import set_process_title
from .worker import Worker
from .cron_scheduler import CronScheduler
def runner(log, log_filename_fn, touch_filename_fn):
# Set a dummy title now; multiprocessing wil... |
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from taggit.managers import TaggableManager
# Create your models here.
class category (models.Model) :
name = models.CharField(max_length=255)
def __str__ (self) :
return self.name
class Post(models... |
from getpass import getpass
from scipy.io import readsav
import requests
import os
import pickle
import logging
import warnings
logging.captureWarnings(True)
logging.basicConfig(format='%(asctime)s: %(message)s', datefmt='%d-%b-%y %H:%M:%S', level=logging.INFO)
def mms_login_lasp(always_prompt=False):
'''
Th... |
"""
Exceptions that may be raised by the Blockstore API
"""
class BlockstoreException(Exception):
pass
class NotFound(BlockstoreException):
pass
class CollectionNotFound(NotFound):
pass
class BundleNotFound(NotFound):
pass
class DraftNotFound(NotFound):
pass
class BundleFileNotFound(NotF... |
# -*- coding: UTF-8 -*-
import re
import traceback
import simplejson as json
import time
from threading import Thread
from django.db import connection
from django.utils import timezone
from sql.utils.group import auth_group_users
from common.config import SysConfig
from sql.utils.dao import Dao
from common.utils.co... |
#!/usr/bin/env python3
# Copyright 2021 Canonical
# See LICENSE file for licensing details.
import logging
import subprocess
from ops.charm import CharmBase, HookEvent, RelationEvent
from ops.main import main
from ops.model import ActiveStatus, Container, ModelError
from ops.pebble import APIError, ConnectionError, ... |
class matrix:
def __init__(self, list2d):
self._values = [row[:] for row in list2d]
def __repr__(self):
return self._values
def shape(self):
pass |
from vsensortag import vsensor
import ast
import time
class VirtualSensorTag():
def __init__(self, addr, port):
self.accelerometer_sensor = vsensor.VirtualAccelerometerSensor(addr, port)
self.humidity_sensor = vsensor.VirtualHumiditySensor(addr, port)
self.magnetometer_sensor = vsensor.VirtualMagnetomete... |
import pytest
from cekit.config import Config
def test_config_key_not_available():
config = Config()
config.configure("/dev/null", {})
with pytest.raises(KeyError) as e_info:
config.get("not_exists", "key")
assert e_info == "'/not_exists' section doesn't exists in Cekit configuration!"
... |
class AuthenticationTokenNotFound(Exception):
def __init__(self):
super().__init__('Authentication token not found')
class UserNotLoggedIn(Exception):
def __init__(self):
super().__init__("User not logged in")
class ApiError(Exception):
DEFAULT_MSG = "Can't complete the petition"
de... |
# Copyright (c) 2013 Amazon.com, Inc. or its affiliates.
# All Rights Reserved
#
# 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... |
# Fréchet Resnet Distance (FRD)
# Based on: https://ww2.mathworks.cn/matlabcentral/fileexchange/31922-discrete-frechet-distance
import torch
from torchvision.models import resnet50
from torch.nn.functional import adaptive_avg_pool2d
import numpy as np
#// TODO: RecursionError: maximum recursion depth exceeded in comp... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-26 17:52
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blockchain', '0012_remove_medication_public_key'),
]
operations = [... |
"""fitsdiff is now a part of Astropy.
Now this module just provides a wrapper around astropy.io.fits.diff for backwards
compatibility with the old interface in case anyone uses it.
"""
import os
import sys
from astropy.io.fits.diff import FITSDiff
from astropy.io.fits.scripts.fitsdiff import log, main
PY3K = sys.ver... |
import sys
import time
with open ('./logicVerilog/prm_lgcchk_top.v','w') as vFile:
vFile.write('module prm_lgcchk_top\n(\ninput A,\ninput B,\ninput C,\ninput D,\ninput E,\ninput F,\ninput G,\ninput H,\ninput I,\ninput J,\ninput K,\ninput L,\ninput M,\ninput N,\ninput O,\noutput [1023:0] edge_mask\n);\n')
for k in r... |
from __future__ import division, print_function, absolute_import
from past.builtins import range
'''
Author : Lyubimov, A.Y.
Created : 07/08/2016
Last Changed: 10/30/2018
Description : IOTA GUI controls
'''
import os
import wx
import wx.richtext
import wx.lib.agw.floatspin as fs
import wx.lib.agw.ultimatelis... |
from . import objtypes
# common exception types
Arithmetic = objtypes.TypeTT('java/lang/ArithmeticException', 0)
ArrayOOB = objtypes.TypeTT('java/lang/ArrayIndexOutOfBoundsException', 0)
ArrayStore = objtypes.TypeTT('java/lang/ArrayStoreException', 0)
ClassCast = objtypes.TypeTT('java/lang/ClassCastException', 0)
MonS... |
# -*- coding: utf-8 -*-
"""Simple functions to detect, replace, remove, or convert to code point a string containing unicode emojis or emojis that are supported by Discord.
https://static.emzi0767.com/misc/discordEmojiMap.min.json
"""
from .resources import emojis, sijome
import re
_PATTERN = None
def _cleaned(na... |
import datetime
import hashlib
import os
import bcrypt
from . import *
# define many-to-many relationship
users_to_applications = db.Table('user_to_applications',
db.Column('user_id',
db.Integer,
db.F... |
# Copyright 2021 Peizhi Yan. 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... |
#!/usr/bin/env python
# encoding=utf-8
from __future__ import print_function, unicode_literals
from collections import namedtuple
from itertools import cycle
import jinja2
from PIL import Image
Point = namedtuple('Point', ['x', 'y'])
Pixel = namedtuple('Pixel', ['r', 'g', 'b'])
RenderItem = namedtuple('RenderItem',... |
# This file is just a proof-of-working file for animating.
from mpl_toolkits.mplot3d import axes3d
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import cm
def generate(X, Y, phi):
R = 1 - np.sqrt(X**2 + Y**2)
return np.cos(2 * np.pi * X + phi) * R... |
reference_line = 0.0
def conversion(state):
x = state[0]
y = state[1]
theta = state[2]
s = x
rho = y
return s, rho, theta
|
# BAREOS - Backup Archiving REcovery Open Sourced
#
# Copyright (C) 2019-2020 Bareos GmbH & Co. KG
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of version three of the GNU Affero General Public
# License as published by the Free Software Foundation and included... |
import os
import shutil
import tempfile
from typing import List, Tuple
from pydantic import BaseModel, Field
from rdkit import Chem
from copy import deepcopy
from icolos.utils.enums.step_enums import StepAutoDockVinaEnum, StepBaseEnum
from icolos.utils.execute_external.autodockvina import AutoDockVinaExecutor
from ic... |
import numpy as np
from .base import ScalarField
class NormalsScalarField(ScalarField):
def extract_info(self):
self.normals = self.pyntcloud.points[["nx", "ny", "nz"]].values
class InclinationDegrees(NormalsScalarField):
""" Vertical inclination with respect to Z axis in degrees.
"""
def co... |
# -*- coding: utf-8 -*-
from contextlib import nullcontext as does_not_raise
from io import BytesIO
import logging
import pytest
from nightshift.comms.storage import get_credentials, Drive
from nightshift.ns_exceptions import DriveError
@pytest.mark.firewalled
class TestDriveLive:
def test_list_src_directory(se... |
from rest_framework import serializers
from django.conf import settings
from .models import Photo
# serializer classes goes here
class PhotoSerializer(serializers.ModelSerializer):
image_url = serializers.SerializerMethodField('get_the_image_url')
def get_the_image_url(self, obj):
return '%s%s' % (... |
class Solution:
# @param A : tuple of integers
# @return an integer
def longestConsecutive(self, A):
result, lengths = 1, {key: 0 for key in A}
for i in A:
if lengths[i] == 0:
lengths[i] = 1
left, right = lengths.get(i - 1, 0), lengths.get(i + 1, 0... |
import numpy as np
import scipy as sp
from scipy.linalg import null_space
import FrankWolfeCoreset as FWC
import copy
import time
from FastEpsCoreset import sparseEpsCoreset
SMALL_NUMBER = 1e-7
def checkIfPointsAreBetween(p, start_line, end_line):
return (np.all(p <= end_line) and np.all(p >= start_line)) or (np... |
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
#
# Solution to Project Euler problem 5
# Copyright (c) Project Nayuki. All rights reserved.
#
# https://www.... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Derived from nsVersionComparator.cpp in mozilla-central
from itertools import izip_longest
import re
__all__ = 'Ver... |
from pygrading import Job
job = Job()
job.verdict("Accept")
job.score(100)
job.comment("Hello World")
job.print()
|
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from os import environ
MARIADB_DATABASE_URI = f'mysql+pymysql://{environ.get("DATABASE_USER")}:{environ.get("DATABASE_PASS")}@{environ.get("DATABASE_HOST")}:{environ.get("DATABASE_PORT")... |
"""
Created by Edward Li at 8/23/20
"""
import numpy as np
def ReLU(Activation):
def activation_fn(self, inputs):
# ReLU(x) = 0 if x <= 0
# x else
return np.maximum(inputs, 0)
def activation_prime(self, inputs):
# dReLU(x) = 0 if x<=0
# 1 else
... |
# Generated by Django 3.1.7 on 2021-04-03 14:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('awwward', '0001_initial'... |
""" TDT4113: Project 5 - Keypad """
class Rule:
""" Defines structure for a Rule used in the FSM """
def __init__(self, state1, state2, signal, action=None):
self.state1 = state1
self.state2 = state2
if signal == "¤":
self.signal = self.signal_is_valid_led
elif sign... |
#!/usr/bin/env python3
import rospy
import std_msgs.msg
import sensor_msgs.msg
import geometry_msgs.msg
import lstm_visual_servoing.msg
import tf
import pyquaternion
import math
import numpy as np
import time
class StateMachine:
def __init__(self):
rospy.init_node('state_maching', anonymous=False)
... |
import time
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from torch.nn import init
class BiLSTM_CRF_Size(nn.Module):
def __init__(self, args):
super(BiLSTM_CRF_Size, self).__init__()
for k, v in args.__dict__.items():
self.__se... |
## @ingroup Methods-Utilities
#soft_max.py
#Created: Feb 2016, M. Vegh
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
import numpy as np
# ------------------------------------------------------------------... |
# Copyright 2018-2019 The glTF-Blender-IO 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 applicable law or ... |
import numpy as np
class GradientDescent:
""" Base Model:
X: array_like
The input dataset of shape (m x n+1), where m is the number of examples,
and n is the number of features. We assume a vector of one's already
appended to the features so we have n+1 columns.
y: array_like
... |
# Generated by Django 2.0.4 on 2018-05-06 07:36
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='UserInfo',
fields=[
('id', models.AutoField... |
my_dictionary={
"nama": "Elyas",
"tinggal": "Probolinggo",
"year": 2000
}
print(my_dictionary)
my_dictionary= {'warna': 'merah',
1: [2,3,5]}
print(my_dictionary[1][-1]) |
#|==============================================================|#
# Made by IntSPstudio
# Two Player Game Results
# Thank you for using this software!
# Version: 0.0.9.20170506
# ID: 980005010
#
# Twitter: @IntSPstudio
#|==============================================================|#
#IMPORT
import sys
import it8c
i... |
from gi.repository import GLib
try:
# We need a real thread, even if gevent has monkeypatched threads.
from gevent.threadpool import ThreadPoolExecutor
except ImportError:
from concurrent.futures import ThreadPoolExecutor
def worker():
GLib.MainLoop().run()
def launch():
executor = ThreadPoolExecutor(max_worke... |
from IO.Write import *
from IO.Reader import *
from Processing.Generator import *
from Processing.Detector import *
from Drivers.SpecInfoDisplayDriver import *
import tkinter as tk
if __name__ == '__main__':
# Устанавливаем окно и обьект графиков
window = tk.Tk()
window.title("Методы обработки эксперим... |
"""
Helper for loading our test files
"""
import os
HERE = os.path.dirname(os.path.abspath(__file__))
def get_reports():
return [x for x in os.listdir(HERE) if x.endswith(".xml")]
def get_filepath(filename):
"""
:param filename:
:return:
"""
return os.path.join(HERE, filename)
|
#!/usr/bin/env python
import numpy as np
from pycrazyswarm import *
import pycrazyswarm.cfsim.cffirmware as firm
import uav_trajectory
TIMESCALE = 1.0
POSITIONS = [
[0, 1.0, 1.5],
[0.25, 0.5, 2.37],
[0.25, -0.5, 2.37],
[-0.25, 0.5, 0.63],
[-0.25, -0.5, 0.63],
[0, -1.0, 1.5]
]
OFFSET = [0.0,... |
from typing import Callable
from vector import Vec2d, Color
import pygame
class Text:
small_font = pygame.font.SysFont('Tahoma', 16)
medium_font = pygame.font.SysFont('Tahoma', 32)
large_font = pygame.font.SysFont('Tahoma', 64)
@staticmethod
def label(text, color, font=small_font):
return font.render(str(text... |
import os
import platform
class traceip():
def tracert():
if platform.system() == 'Windows':
return os.system('tracert '+input('請輸入目標ip或網域 : '))
elif platform.system() == 'Linux':
return os.system('traceroute '+input('請輸入目標ip或網域 : ')) |
"""Author: WKirgsn, 2018
Hands-On Training with Recurrent Neural Networks"""
import warnings
warnings.filterwarnings("ignore")
import preprocessing.config as cfg
import gc
import numpy as np
from preprocessing import select_gpu # choose GPU through import
from keras.callbacks import EarlyStopping, ReduceLROnPlateau
f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class OpenFormFieldDO(object):
def __init__(self):
self._optional = None
self._required = None
@property
def optional(self):
return self._optional
@optional.setter... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
PKG_NAME = 'ssh_proxy'
PKG = __import__(PKG_NAME)
setup(
name=PKG_NAME,
version=PKG.__version__,
description='',
author='Noble Code',
maintainer='Andrey Ovchinnikov',
maintainer_email='andrey@noblecode.ru',
packages=find_... |
from django.db.models import signals
from commands.sync_plugins import sync_app_plugins
from app_plugins import models as sender_app
def do_sync(*args, **kwdargs):
sync_app_plugins()
signals.post_syncdb.connect(do_sync, sender=sender_app)
if __name__ == "__main__":
sync_app_plugins()
|
from setuptools import setup, find_packages
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3'
]
setup(
name='osm2paths',
version='0.0.11',
descripti... |
import os
from django.utils._os import safe_join
from django.core.files.base import ContentFile
from django.core.files.storage import FileSystemStorage
from django.contrib.staticfiles.finders import FileSystemFinder
from . import app_settings
from .utils import render
class DotdStorage(FileSystemStorage):
def _... |
"""Module for polling display metrics"""
import tempfile
import ctypes
from mss import mss
from utilities.log import LOGGER
from config import HOSTNAME
LOG_PREFIX = "[display]"
################################################################
class AgentModule:
"""Agent class for display sensors"""
name = "... |
from collections import namedtuple
from typing import Optional, List
import numpy as np
import scipy
import tensorflow as tf
import gpflow
from gpflow import default_float
from gpflow.utilities import to_default_float
from .util import gower_factor, quantile_normalize
from .score_test import ScoreTest
from .optimize... |
"""rhw URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based v... |
# -*- coding: utf-8 -*-
from datetime import timedelta, datetime
import pandas as pd
from fooltrader.bot.bot import NotifyEventBot
from fooltrader.contract.es_contract import get_es_kdata_index, get_es_statistic_index
from fooltrader.domain.data.es_quote import CommonKData, CommonStatistic
from fooltrader.settings im... |
# Generated by Django 3.0.5 on 2020-04-11 17:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='job',
name='salary',
field=m... |
import unittest
from unittest.mock import MagicMock
from account_verification_flask.models.models import User
from account_verification_flask.services.authy_services import AuthyServices
from .base import BaseTestCase
class AuthyTests(BaseTestCase):
def test_unverified_user_with_valid_code_then_gets_verified(... |
start = 3
total = 0
for i in range(start, -1, -1):
total -= i*i
print(total)
|
with open("input") as file:
mem_list = list(map(lambda x: int(x), file.read().split("\t")))
prev_configurations = []
cycles = 0
while mem_list not in prev_configurations:
prev_configurations.append(mem_list[:])
value = max(mem_list)
index = mem_list.index(value)
mem_list[... |
#!/usr/bin/env python
#=============================================================================#
# #
# NAME: vriCalc.py #
# ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.