content stringlengths 5 1.05M |
|---|
# exc. 5.3.5
def distance(num1, num2, num3):
ans1 = abs(num2 - num1)
ans2 = abs(num2 - num3)
ans3 = abs(num3 - num1)
ans4 = abs(num3 - num1)
if ans1 == 1 or ans3 == 1:
if ans1 >= 2 and ans2 >= 2 or ans3 >= 2 and ans4 >= 2:
return True
return False
pri... |
#!/usr/bin/python
#Created : Wed 05 Nov 2008 08:31:22 PM GMT
#Last Modified : Wed 05 Nov 2008 09:37:17 PM GMT
#qpy:2
#qpy:console
import site
import os
import sys
#from time import strftime
from pyPdf import PdfFileWriter, PdfFileReader
output = PdfFileWriter()
if len(sys.argv) < 4:
print "Begini boh: %s fail_asal ... |
from django.utils.deprecation import MiddlewareMixin
from django.utils import timezone
from accounts.models.user_profile import ClubUserProfile
from accounts.models import Messages
class ManageMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.user.is_authenticated:
t... |
from setuptools import setup, find_packages
setup(
name='sampi',
version='0.1.0',
author='Jonathan Lindbloom',
author_email='jonathan@lindbloom.com',
license='LICENSE',
packages=find_packages(),
description='A personal Python package for computational math-related things.',
long_descrip... |
import bnd_rebuilder
import unittest
from bnd_rebuilder import unpack_bnd
from bnd_rebuilder import repack_bnd
# Comsume byte unit tests
class consume_byte_unit_tests(unittest.TestCase):
def setUp(self):
self.consume_byte_instance = bnd_rebuilder.consume_byte
return super().setUp()
def tearDown... |
import os
import logging
import time
import string
import traceback
from buttons import BTNS
from pyrogram import Client, filters
import datetime
from pyrogram.errors import UserNotParticipant, ChatAdminRequired, UsernameNotOccupied
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from config impor... |
# Copyright 2020 Tony Astolfi
#
import csv
import matplotlib.pyplot as plt
import matplotlib
with open('avail_model_85.csv') as fp:
r = csv.reader(fp)
d85 = [d for d in r]
d85 = [(int(n), float(p)) for n, p in d85[1:]]
(n_odd, a85_odd) = zip(*d85[:25])
(n_even, a85_even) = zip(*d85[25:])
with open('avail_mod... |
#!/usr/bin/env python3
# JM: 30 Aug 2018
# process the *scalar.nc files (because I couldn't get XIOS to spit out just
# a number for whatever reason...)
import netCDF4
import glob, sys
#--------------------------------------------------------
# define the argument parser
import argparse
parser = argparse.ArgumentPa... |
# --------------------------------------------------------------------------
# Source file provided under Apache License, Version 2.0, January 2004,
# http://www.apache.org/licenses/
# (c) Copyright IBM Corp. 2015, 2020
# --------------------------------------------------------------------------
# gendoc: ignore
impo... |
#!/usr/bin/env python
# -*- encode: utf-8 -*-
#Copyright 2015 RAPP
#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 applicabl... |
#coding:utf-8
'''
filename:comprehension.py
chap:4
subject:18
conditions:
solution:
'''
#找出[2,4,-7,19,-2,-1,45]中小于0的数
lst = [2,4,-7,19,-2,-1,45]
print([i for i in lst if i<0])
#找出{'python':89,'java':58,'physics':65,'math':87,'chinese':74,'english':60}大于平均分的学科
scores = {'python':89,'java':58,... |
"""
A utility function for walking a simplified document
"""
from inspect import signature
def walk(document, fun, TYPE="document", no_iter=None):
"""
Walk an document tree and apply a function to matching nodes
:param document: Simplified Docx element to walk
:type document:object
:param fun: A ... |
"""
:mod:`frbr` Models for FRBR Redis datastore
"""
__author__ = "Jeremy Nelson"
import datetime,os,logging
import redis,urllib2
import namespaces as ns
import common
from lxml import etree
FRBR_RDF_URL = 'http://metadataregistry.org/schema/show/id/5.rdf'
def load_rdf(rdf_url=FRBR_RDF_URL):
"""
Function ta... |
from spider.collector.data_collector import DataRecord
from spider.conf import SpiderConfig
from spider.conf.observe_meta import EntityType, ObserveMetaMgt
from spider.data_process.prometheus_processor import PrometheusProcessor
from spider.entity_mgt import ObserveEntityCreator
from .common import assert_data_record, ... |
from __future__ import absolute_import, division, print_function
import sys
from subprocess import check_call
from glue.tests.helpers import requires_qt
from .._deps import Dependency, categories
class TestDependency(object):
def test_installed(self):
d = Dependency('math', 'the math module')
... |
# -*- coding: utf-8 -*-
import mock
from typing import Any
from zerver.lib.attachments import user_attachments
from zerver.lib.test_classes import ZulipTestCase
from zerver.models import Attachment
class AttachmentsTests(ZulipTestCase):
def setUp(self):
# type: () -> None
user_profile = self.ex... |
# -*- coding: utf-8 -*-
import random
from src.sprites.characters.behaviours.RavenBehaviourState import *
from src.sprites.Character import *
from src.sprites.MySprite import *
from src.sprites.EnemyRange import *
# ------------------------------------------------------------------------------
# Clase RavenFollowPlay... |
#!/usr/bin/env python
# Written by Ken Yin
import os
import pydot
import psutil
import subprocess
import importlib
import pkgutil
import inspect
import apt
import argparse
import random
import string
from simulator.builders import BuilderBase, BuilderSelector
from simulator.utilities.ImageDepot import ImageDepot
from ... |
from django.conf import settings
DRF_HAYSTACK_NEGATION_KEYWORD = getattr(settings, "DRF_HAYSTACK_NEGATION_KEYWORD", "not")
GEO_SRID = getattr(settings, "GEO_SRID", 4326)
|
'''OpenGL extension NV.pixel_data_range
Overview (from the spec)
The vertex array range extension is intended to improve the
efficiency of OpenGL vertex arrays. OpenGL vertex arrays' coherency
model and ability to access memory from arbitrary locations in memory
prevented implementations from using DMA (Direct ... |
"""Run the trade functions based on information gained from the other scripts."""
import configparser
import ccxt
# import time
# from threading import Timer
# import release_trader.check_availability as ca
# import logging
# import gate_api
config = configparser.ConfigParser()
config.read_file(open(r"../.user.cf... |
# Dependencies
from src.dataset import MNIST, ToTensor, train_test_split
from torch.utils.data import DataLoader
from torch.nn.functional import mse_loss, binary_cross_entropy
from torch import nn, optim
import torch
import matplotlib.pyplot as plt
import numpy as np
import tqdm
import time
import os
class AutoEncode... |
"""
Provide computer status info.
To get network upload and download speeds, speedtest-cli app should be installed
"""
#!/usr/bin/env python
import operator
import os
import threading
import time
from collections import deque
from pprint import pprint
import psutil
import platform
from stream2py import Sourc... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import django.conf.locale
from .base import * # noqa isort:skip @UnusedWildImport
LANGUAGES = [("ach-ug", "In-context translation")] # noqa
EXTRA_LANG_INFO = {
"ach-ug":... |
import sys
import traceback
from django.core.management.base import BaseCommand, CommandParser
from devproject.core.selectors import get_registered_developers
from devproject.core.services import sync_developer
ERROR_CODE_MISSING_INPUT = 1
class Command(BaseCommand):
help = "creates or updates local developer ... |
from marshmallow import fields, Schema
from . import db
from .x import course_x_group, teacher_x_course
from .db_class_base import db_class_base
class study_course(db.Model, db_class_base):
__tablename__ = 'study_courses'
_id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), null... |
from flask import request, jsonify
from .base import Base
from .json_validate import SCHEMA
from jybase.utils import validate_hash_key, create_md5_key, create_hash_key
from config import config
class StoreSessions(Base):
def post(self):
# TODO: add sms login
is_valid, data = self.get_params_fr... |
from django.urls import path, re_path, include
from .ajax_util import get_all_ajax_functions
from .views import (
get_boxes_codes,
get_clerk_codes,
get_counter_commands,
checkout_view,
overseer_view,
vendor_view,
accept_terms,
get_items,
all_to_print,
item_add,
item_hide,
... |
from TschunkView import *
from CodeView import *
import time
t = TschunkView(TschunkMap1())
#c = CodeView(TschunkMap1())
direction = 0
def simple_main():
print 'thread started!'
direction = -1
while True:
time.sleep(1)
if not t.move((0,direction)):
direction *= -1
def move():
... |
"""Test for the IP functions."""
import pytest
from netutils import ip
IP_TO_HEX = [
{
"sent": {"ip": "10.1.1.1"},
"received": "a010101",
},
{
"sent": {"ip": "2001:db8:3333:4444:5555:6666:7777:8888"},
"received": "20010db8333344445555666677778888",
},
]
IP_ADDITION = [... |
from __future__ import absolute_import
from ScopeFoundry.base_app import BaseMicroscopeApp, BaseApp
from .measurement import Measurement
from .hardware import HardwareComponent
from .logged_quantity import LoggedQuantity, LQRange, LQCollection |
import RPi.GPIO as GPIO
from time import sleep
import time, math,sys,os
dist_meas= 0.0
km_per_hour=0
rpm=0
pulse=0
sensor=2
elapse=0
rate=0
start_time= time.time()
def init_GPIO():
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(sensor,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
def calculate_time(... |
import secrets
import gym
import numpy as np
from gym import spaces
from gym.utils import seeding
class HouseEnv(gym.Env):
def __init__(self, X, y, seed=None):
self.seed(seed)
self.X = X
self.y = y
self.random = secrets.SystemRandom(seed)
self.reset()
def seed(self, ... |
# coding: utf-8
"""
Experimental Looker API 3.1 Preview
This API 3.1 is in active development. Breaking changes are likely to occur to some API functions in future Looker releases until API 3.1 is officially launched and upgraded to beta status. If you have time and interest to experiment with new or modifie... |
from __future__ import unicode_literals
from subprocess import call
from itertools import izip
import argparse
import json
import csv
import pysolr
import gzip
INDEX_NAME = 'entityawareindex'
INDEX_MAP = ["ID", "TITLE", "URL", "PUBLISHER", "CATEGORY", "STORY", "HOSTNAME", "TIMESTAMP"]
SOLR_URL = 'http://localhost:898... |
"""Copyright 2008 Orbitz WorldWide
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, software... |
import math
import numpy as np
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as pb
import random
from datetime import datetime
import time
def dist(x, y, pos):
return math.sqrt((pos[0]-x)**2 + (pos[1]-y)**2)
areaSize=(30, 30)
node_posi... |
#!/usr/bin/env python
'''
Module containing simple statistical calculations
Author: Sid Narayanan < sidn AT mit DOT edu >
'''
import ROOT as root
#import root_numpy as rnp
import numpy as np
from PandaCore.Tools.Misc import *
from RooFitUtils import *
from numpyUtils import *
class SimpleVar(object):
'''
... |
import numpy as np
from scipy import linalg as sciLinalg
from dataio import DataIO
class ClosedForm(object):
""" Closed Form solution of regression problem.
Polynomial Fitting
y(x, w) = w0 + w1 x^1 + w2 x^2 ... wM x^M (order M)
-> compute weights wj
SOLVE
- read input and target vector
... |
val = 100
print(val.__hash__())
print("falcon".__hash__())
print((1,).__hash__()) |
#!/usr/bin/env python
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2009,2010,2011,2012,2013,2014,2015,2016,2017 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with... |
import homework.divisor_master as dm
do_this = True
while do_this:
a = int(input("Введите нижнюю границу диапазона "))
b = int(input("Введите верхнюю границу диапазона "))
c = int(input(f"Введите число для обработки в заданном диапазоне от {a} до {b} "))
num = dm.set_num_range(c, a, b)
if dm.is_p... |
import xml.etree.ElementTree as ET
from programy.parser.template.nodes.base import TemplateNode
from programy.parser.template.nodes.richmedia.reply import TemplateReplyNode
from programytest.parser.template.graph_tests.graph_test_client import TemplateGraphTestClient
class TemplateGraphReplyTests(TemplateGraphTestC... |
from conans import ConanFile, tools
from conans.errors import ConanInvalidConfiguration
import os
class SmlConan(ConanFile):
name = "sml"
description = "[Boost].SML: C++14 State Machine Library"
topics = ("conan", "sml", "state-machine")
url = "https://github.com/bincrafters/conan-sml"
homepage = ... |
"""
TODO
"""
from pyderl.utils.data_structures.segment_tree import SegmentTree
from pyderl.utils.data_structures.segment_tree import SumSegmentTree
from pyderl.utils.data_structures.segment_tree import MinSegmentTree
|
import io
import logging
import logging.config
import os
import yaml
class Logger:
YAML_PATH = os.path.join(os.path.dirname(__file__), 'config', 'mylogger_config.yml')
string_io = io.StringIO()
def __init__(self) -> None:
"""
1. Create the logger based on the configuration provided if app... |
import json
import os
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State, MATCH
import plotly.express as px
import pandas as pd
## DATA FROM https://github.com/CSSEGISandData/COVID-19/tree/master/csse_covid_19_data/csse_covid_19_time_... |
from PyQt5.QtCore import Qt, QPointF, QRectF
from PyQt5.QtWidgets import QGraphicsItem, QGraphicsRectItem
from PyQt5.QtGui import QTransform, QPen
from .tile import Cell
class Piece(QGraphicsItem):
tileStates = [1, 2, 3, 1, 2, 3, 1]
coords = [
[
[[0, 1], [0, 0], [1, 0], [-1, 0]],
[[0, 1], [0, 0], [... |
from bs4 import BeautifulSoup
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
def main():
options = Options()
options.add_argument('--incognito')
options.headless = True
options.page_load_... |
from collections.abc import Sequence
from pyball.fundamentals.base_fundamental import BaseFundamental
class CompetitionNews(BaseFundamental):
def __init__(self, soup):
super(CompetitionNews, self).__init__(soup)
self.news_list = []
self.process()
def process(self):
news = self... |
__author__ = 'huyheo'
#*****************
#intent definition
#*****************
TO_GO_SOMEWHERE = 'go_to_some_where'
TIME_INFO = 'time_info'
DISTANCE_INFO ='distance_info'
DURATION_INFO = 'duration_info'
METHOD_TO_GO = 'method_to_go'
DOING_SMTH = 'doing_smth'
AGE_INFO = 'age_info'
#personal assistant
ASK_WHAT_SHOULD_I_D... |
# -*- coding: utf-8 -*-
import requests
url="http://127.0.0.1:8080/predict"
files = {'file':('image.jpg',open("images/7.jpg",'rb'),' image/jpeg')}
r = requests.post(url,files=files)
print(r.text)
|
from taichi.type.annotations import *
from taichi.type.primitive_types import *
|
__all__ = ['get_orientation',
'reorient_image2',
'get_possible_orientations',
'get_center_of_mass']
import numpy as np
from tempfile import mktemp
from . import apply_transforms
from .. import utils
from ..core import ants_image as iio
_possible_orientations = ['RIP','LIP', 'RSP... |
# user-agent (www.useragentstring.com) : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36
import requests
from bs4 import BeautifulSoup # beautifulsoup : python library for pulling data from html and xml files. it works with a parser.
import bs4.element
... |
str = "this is a string example... wow!!"
print(str.find('example')) |
import pytest
from cryptokey.backend.cryptography import hashes as backend
from hashvectors import check_vector, hash_vectors
@pytest.mark.parametrize("vector", hash_vectors)
def test_vectors(vector) -> None:
try:
check_vector(vector, backend, backend.CryptographyHash)
except NotImplementedError:
... |
import os
import github3
from github3 import repos
from datetime import datetime
from tests.utils import (BaseCase, load, mock)
class TestRepository(BaseCase):
def __init__(self, methodName='runTest'):
super(TestRepository, self).__init__(methodName)
self.repo = repos.Repository(load('repo'))
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
def main():
setup(
name="spentfuelgpr",
version="0.1",
description="Python part of the MIsoEnrichment module",
author="Nuclear Verification and Disarmament Group, RWTH Aachen University",
url="https:... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
"""
URL route definitions for api_v2
Of importance (and perhaps in error) the OAuth2 endpoints are
including underneath the `/api_v2` url segment.
In theory this will allow us to use a different OAuth2 mechanism
for future versions of the API with less friction. We will see
how that plays out in practice.
"""
from ... |
##############################################################################################################################
# Author: Roni Haas
# Main goal: Takes several pileup files and for each one prints to a new file only unique sites (that is, only sites that are
# not in any of the other pileup files
#####... |
# 821. Shortest Distance to a Character
# ttungl@gmail.com
# Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.
# Example 1:
# Input: S = "loveleetcode", C = 'e'
# Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
# Note:
# S string le... |
import numpy as np
from pathlib import Path
from sklearn.preprocessing import LabelEncoder
DATA_DIR = Path('data')
def create_cleaned_df(df, class_label_str):
"""Transform the wide-from Dataframe (df) from main.xlsx into one with
unique row names, values 0-1001 as the column names and a label column
conta... |
import sys
import json
import numpy as np
from tqdm import tqdm
import utils.load_info_for_model
from candidate_generator import random_walk
def evaluate(playlists, candidate_generator):
sizes = [10, 100, 500, 1000, 5000, 10000, 20000, 30000]
metrics = [[], [], [], [], [], [], [], []]
for i, playlist in... |
from datasets import DataProvider
if __name__ == "__main__":
hparams = {
"dataset": {
'name': "Urban100",
'test_only': True,
'patch_size': 96,
'ext': 'sep',
'scale': 2,
"batch_size": 16,
'test_bz': 1,
'train_bz'... |
from flask import Blueprint
from . import is_api
from methods import content
from methods.board import if_board_exist
from constants import messages
ai_content_blueprint = Blueprint('AI_Content', __name__)
@ai_content_blueprint.route('/test', methods=['GET'])
def test():
return if_board_exist('1. 머신러닝')
@ai_co... |
from lgsf.councillors.scrapers import ModGovCouncillorScraper
class Scraper(ModGovCouncillorScraper):
base_url = "http://applications.huntingdonshire.gov.uk/moderngov/"
|
""" DEMO text adventure game """
from text_adventure_parser.text_util import list_to_text
from demo_game.engine import Engine
DIVIDER = "\n" + ("-" * 50) + "\n"
def main():
"""The game loop"""
game = Engine()
print(DIVIDER)
print("Welcome to the game brave adventurer!")
print("Type 'help' or '?... |
def mnn_concatenate(*adatas, geneset=None, k=20, sigma=1, n_jobs=None, **kwds):
"""Merge AnnData objects and correct batch effects using the MNN method.
Batch effect correction by matching mutual nearest neighbors [Haghverdi18]_
has been implemented as a function 'mnnCorrect' in the R package
`scran ... |
import asyncio
import functools
import re
from . import constants as const
from .pool import MemcachePool
from .exceptions import ClientException, ValidationException
__all__ = ['Client']
def acquire(func):
@asyncio.coroutine
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
conn = yi... |
class Matrix:
def __init__(self, data):
self.matrix = []
self.m = 0 #number of rows
self.n = 0 #number of columns
if ";" in data: #if ";" exists, there is more than 1 row in the matrix
self.m = len(data.split(";")) #count the number of rows in the input
self.n... |
'''
Created on May 26, 2017
@author: Tim
'''
import os
from os.path import join
from praatio import tgio
from praatio import audioio
from praatio import praatio_scripts
root = r"C:\Users\Tim\Dropbox\workspace\praatIO\examples\files"
audioFN = join(root, "mary.wav")
tgFN = join(root, "mary.TextGrid")
outputPath = j... |
from django.core.files.uploadedfile import UploadedFile
from formtools.wizard.storage.exceptions import NoFileStorageConfigured
from formtools.wizard.storage.session import SessionStorage
class MultiFileSessionStorage(SessionStorage):
"""Custom formtools storage to handle multiple file uploads.
The `formtool... |
kernel_forward = '''
extern "C"
__global__ void roi_forward(const float* const bottom_data,const float* const bottom_rois,
float* top_data, int* argmax_data,
const double spatial_scale,const int channels,const int height,
const int width, const int pooled_he... |
from drf_yasg.openapi import Parameter
from drf_yasg.utils import swagger_auto_schema
from rest_framework import authentication, permissions, viewsets, mixins
from rest_framework.decorators import action
from rest_framework.response import Response
from core.models import Notebook, Member
from notebook.serializers.fol... |
from pySDC.core.Errors import TransferError
from pySDC.core.SpaceTransfer import space_transfer
from pySDC.implementations.datatype_classes.parallel_mesh import parallel_mesh, parallel_imex_mesh
from mpi4py_fft import PFFT, newDistArray
import numpy as np
class fft_to_fft(space_transfer):
"""
Custon base_tran... |
import utils
import functions as func
from commands.base import Cmd
help_text = [
[
("Usage:", "<PREFIX><COMMAND> `NEW WORD`"),
("Description:",
"If you use `@@game_name@@` in your channel name templates, when no game is detected or "
"there are multiple games being played, the wo... |
import os, sys, subprocess, getpass, paramiko, re
from collections import OrderedDict
# Log helpers
class colors:
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
PURPLE = "\033[35m"
CYAN = "\033[36m"
GRAY = "\033[90m"
ENDC = "\033[0m"
TAG... |
#!/usr/bin/env python
import json
import subprocess
def run(apps_path, out_path):
# Generate www content
cmd = ["python", "-m", "trame.tools.www", "--output", out_path]
subprocess.run(cmd)
# Generate app files index.html => {app_name}.html
with open(apps_path, "r") as rf:
apps_dict = jso... |
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Bar, Timeline, Pie
df = pd.read_csv('G:/PythonFIle/appRank/clearData/tabName.csv', encoding='gbk')
sep = df.shape
l, h = sep[1], sep[0]
print(l, h)
ys = []
x = []
time = []
head = df.columns
for i in range(0, l - 1):
... |
#Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved.
#This program is free software; you can redistribute it and/or modify it under the terms of the BSD 3-Clause License.
#This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty... |
from uuid import uuid4
SECRET_KEY = str(uuid4())
LOGGER_NAME = 'http'
HOST = 'localhost'
PORT = 5000 |
import io
import os.path
from msgpack import packb
import pytest
from .hashindex import H
from .key import TestKey
from ..archive import Statistics
from ..cache import AdHocCache
from ..compress import CompressionSpec
from ..crypto.key import RepoKey
from ..hashindex import ChunkIndex, CacheSynchronizer
from ..helpe... |
import unittest
import numpy as np
from geeksw.utils.data_loader_tools import make_data_loader
class Test(unittest.TestCase):
def test_data_loader_tools(self):
data = {"a": np.array([1, 2, 3]), "b": np.array([2, 3, 4]), "c": np.array([5, 6, 7])}
funcs = {
"d": lambda df: df["a"] + ... |
from os import system
from calcupy import settings
from calcupy import commands
from calcupy import evaluator
from calcupy.variables import NumberVariables, FunctionVariables
from math import sqrt, sin, cos, tan
from math import pi, e
class Calculator:
DEFAULT_NUMBER_VARIABLES = {"pi": pi, "e": e}
DEFAULT_FUN... |
from __init__ import *
class DarkTheme:
@staticmethod
def button(obj: QPushButton):
obj.setStyleSheet("""
QPushButton{
color: #E0E0E0;
border: none;
outline: none;
background-color: #424242;
selection-background-color: #424242;
... |
from unittest import TestCase
from zmodulo.plot.line.end_point import EndPoint
__author__ = 'aruff'
class TestArrow(TestCase):
def test_integer_assignment(self):
"""
Tests the integer initialization of the Arrow class
"""
arrow = EndPoint(0, 0)
self.assertEqual(arrow.to_s... |
# -*- coding: utf-8 -
#
# Copyright (C) 2011 by Saúl Ibarra Corretgé
#
# This file is part of gaffer. See the NOTICE for more information.
import pyuv
import datetime
import errno
import logging
import time
try:
import _thread as thread
except ImportError:
import thread
from collections import deque
import ... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# 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... |
from .HOG import hog |
from copy import deepcopy
import requests
from django.conf import settings
from .utils import check_required_settings
REQUIRED_SETTINGS_POST = ('OPEN311_API_KEY', 'OPEN311_API_SERVICE_CODE', 'OPEN311_API_BASE_URL')
REQUIRED_SETTINGS_GET = ('OPEN311_API_BASE_URL',)
class Open311Exception(Exception):
pass
def ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('mail', '0039_auto_20160203_1417'),
]
operations = [
migrations.AddField(
model_name='checksettings',
... |
import yaml
import subprocess
import glob
import pandas as pd
stream = open('rais/configuration.yaml')
config = yaml.safe_load(stream)
def create_folder_tmp():
path = config['path_output_data']
create_folder(path, 'tmp')
def create_folder_year(year):
path = config['path_output_data'] + 'tmp/'
create... |
import argparse
from ..submission import submit_any_ingestion
from ..base import UsingCGAPKeysFile
EPILOG = __doc__
@UsingCGAPKeysFile
def main(simulated_args_for_testing=None):
parser = argparse.ArgumentParser( # noqa - PyCharm wrongly thinks the formatter_class is invalid
description="Submits a gene ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
from datetime import datetime, timedelta
def read_period_file(file):
""" Opens the .txt file of the period calendar app. This function is meant
for the app Period Tracker of Simple Design Ltd."""
period_cal = []
periods = []
# re... |
import numpy as np
from pymoo.operators.crossover.simulated_binary_crossover import SimulatedBinaryCrossover
from pymoo.operators.sampling.random_sampling import FloatRandomSampling
from pymoo.problems.single import Rastrigin
problem = Rastrigin(n_var=30)
crossover = SimulatedBinaryCrossover(eta=20)
pop = FloatRando... |
>>> con= sqlite3.connect('population2.db')
>>> cur=con.cursor()
>>> cur.execute('''CREATE TABLE PopByRegion (
... Region TEXT NOT NULL,
... Population INTEGER NOT NULL,
... PRIMARY KEY (Region))''')
<sqlite3.Cursor object at 0x7fc0c81907a0>
>>> cur.execute('''
... CREATE TABLE PopByCountry(
... Region TEXT NOT NULL,
..... |
import time
def format_seconds(seconds):
return time.strftime("%H:%M:%S", time.gmtime(seconds)) |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import filter
from future import standard_library
standard_library.install_aliases()
from vcfx import util
from vcfx.field.nodes import Unknown
M_NAMES = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.