content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
DRB1_1385_9 = {0: {'A': -999.0, 'E': -999.0, 'D': -999.0, 'G': -999.0, 'F': -0.004754, 'I': -0.99525, 'H': -999.0, 'K': -999.0, 'M': -0.99525, 'L': -0.99525, 'N': -999.0, 'Q': -999.0, 'P': -999.0, 'S': -999.0, 'R': -999.0, 'T': -999.0, 'W': -0.004754, 'V': -0.99525, 'Y': -0.004754}, 1: {'A': 0.0, 'E': 0.1, 'D': -1.3, '... | python |
from linghelper.phonetics.praat import PraatLoader
from linghelper.phonetics.praat.helper import to_time_based_dict
from scipy.interpolate import interp1d
from numpy import vstack,array
def interpolate_pitch(pitch_track):
defined_keys = [k for k in sorted(pitch_track.keys()) if pitch_track[k]['Pitch'] != '--... | python |
import sys
import web_tests.create_test_suite as tests
import web_tests.csv2_runner as csv2_runner
def main(gvar):
# setup to run Chromium tests
runner = csv2_runner.Csv2TestRunner(verbosity=2, gvar=gvar)
suite = tests.chromium_test_suite()
runner.run(suite)
print()
if __name__ == "__main__":
... | python |
from payment.payment_interface import PaymentInterface
from rest_framework.test import APITestCase
class TestPaymentInterface(APITestCase):
def test_get(self):
res = PaymentInterface.get('https://api.paystack.co/bank')
self.assertEquals(res.get('status'), True)
def test_get_with_auth(self):
... | python |
import numpy as np
from multiprocessing import Pool
from multiprocessing import cpu_count
_user_input = None
_item_input = None
_labels = None
_batch_size = None
_index = None
_dataset = None
# input: dataset(Mat, List, Rating, Negatives), batch_choice, num_negatives
# output: [_user_input_list, _item_inp... | python |
#!/usr/bin/python3
import numpy as np
from os.path import join as pjoin
from os import linesep
from shutil import copyfile
from scipy.io import mmwrite
from scipy.sparse import coo_matrix
import gzip
diri='data/raw'
diro='data/de'
key='celltype'
values=['dysfunctional','naive']
#Load covariate info
dc=np.loadtxt(pj... | python |
__version__ = "0.3.2"
__api_version__ = "0.10.1"
| python |
from aiocloudflare.commons.auth import Auth
class Dnssec(Auth):
_endpoint1 = "zones"
_endpoint2 = "dnssec"
_endpoint3 = None
| python |
#reference: https://github.com/val-iisc/capnet/blob/master/src/proj_codes.py
from __future__ import division
import math
import numpy as np
import torch
import utils.network_utils
class Projector(torch.nn.Module):
'''
Project the 3D point cloud to 2D plane
args:
xyz: float tensor, (BS,N_PTS,... | python |
#!/usr/bin/python
#--2 and 3--
__author__ = "gray"
__date__ = "20171228"
__version__ = "1.0.2"
__aim__ = """
GetData.py for miseq pipeline CHSLAB used
Copy file,
Rename file,
unzip file > for QC used
input:
sample sheet
project Dir (Target Dir)
[sample sheet] format
RawSampleName\tNewSampleName[marker]
"... | python |
# Standard Library
import json
import os
import pstats
import shutil
import time
from multiprocessing.pool import ThreadPool
# Third Party
import boto3
import pandas as pd
import pytest
# First Party
from smdebug.core.access_layer.utils import is_s3
from smdebug.profiler.analysis.python_profile_analysis import Pyinst... | python |
#
# Copyright (c) 2009-2015 Tom Keffer <tkeffer@gmail.com>
#
# See the file LICENSE.txt for your full rights.
#
"""Console simulator for the weewx weather system"""
from __future__ import with_statement
from __future__ import absolute_import
from __future__ import print_function
import math
import random
import ... | python |
from typing import Dict
import psycopg2
import requests
def insert_reading(reading: Dict):
sql = """
INSERT INTO youless_readings (
net_counter,
power,
consumption_high,
consumption_low,
production_high,
p... | python |
import os
import torch
from torch.autograd import Function
import torch.nn as nn
from typing import *
from torch.utils.cpp_extension import load
ppp_ops = load(name="ppp_ops",
sources=[f"{os.path.dirname(os.path.abspath(__file__))}/pointnetpp_operations.cpp",
f"{os.path.dirname(... | python |
import sys
import time
import pprint
from web3 import Web3
from solcx import compile_source
import os
contract_source_path = os.environ['HOME']+'/765_a3/MyContract.sol'
logs = False
grcpt = False
def compile_source_file(file_path):
with open(file_path, 'r') as f:
source = f.read()
return compile_source(s... | python |
import xacc
xacc.Initialize()
# Get access to D-Wave QPU and
# allocate some qubits
dwave = xacc.getAccelerator('dwave')
qubits = dwave.createBuffer('q')
# Define the function we'd like to
# off-load to the QPU, here
# we're using a the QMI low-level language
@xacc.qpu(accelerator=dwave)
def f(buffer, h, j):
... | python |
# -*- coding: utf-8 -*-
'''
Redis SDB module
================
.. versionadded:: 2019.2.0
This module allows access to Redis using an ``sdb://`` URI.
Like all SDB modules, the Redis module requires a configuration profile to
be configured in either the minion or master configuration file. This profile
requires very... | python |
import ast
import os
import logging
from contextlib import contextmanager
from pystatic.arg import Arg, Argument
from typing import List, Tuple
from pystatic.target import Target
from pystatic.symid import symid2list
from pystatic.typesys import TypeClassTemp, TypeFuncTemp, TypeIns, TypeTemp, TypeType
from pystatic.sym... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2012, Rui Carmo
Description: Docstring utility functions
License: MIT (see LICENSE.md for details)
"""
import os, sys, logging
import inspect
from bottle import app
log = logging.getLogger()
def docs():
"""Gather all docstrings related to routes an... | python |
import pytest
from pydantic import ValidationError
from porcupine.base import Serializer
class User(object):
def __init__(self, name=None, surname=None, age=None):
self.name = name
self.surname = surname
self.age = age
class UserSerializer(Serializer):
name: str
surname: str
... | python |
from pkg_resources import parse_version
from configparser import ConfigParser
import setuptools
assert parse_version(setuptools.__version__)>=parse_version('36.2')
# note: all settings are in settings.ini; edit there, not here
config = ConfigParser(delimiters=['='])
config.read('settings.ini')
cfg = config['DEFAULT'... | python |
import json
import requests
__version__ = '1.0.2'
class TelenorWeb2SMSException(Exception):
"""A generic exception for all others to extend."""
def __str__(self):
# Use the class docstring if the exception message hasn't been provided
if len(self.args) == 0:
re... | python |
from functools import partial
from typing import Callable, Tuple
import numpy as np
from hmc.core import for_loop, while_loop
from hmc.integrators.terminal import cond
def step(val: Tuple, zo: np.ndarray, step_size: float, vector_field: Callable) -> Tuple:
"""Single step of the implicit midpoint integrator. Com... | python |
import pandas as pd
from datetime import datetime
import shlex
import subprocess
import requests
from reportlab.pdfgen import canvas
def generateReport(event_ts, keys):
print('printing report')
directory = "./data/"
csv_name = "result.csv"
csvpath = directory + csv_name
csv = pd.read_csv(csvpath)
... | python |
"""regex utils """
import re
def remove_digits(s: str) -> str:
""" removes digits in a string """
return re.sub("\d+", "", s)
| python |
'''
Transcribing DNA into RNA
http://rosalind.info/problems/rna/
Problem
An RNA string is a string formed from the alphabet containing 'A', 'C',
'G', and 'U'.
Given a DNA string t corresponding to a coding strand, its transcribed
RNA string u is formed by replacing all occurrences of 'T' in t with 'U'
in u.
Given: ... | python |
from itertools import product
with open('output.txt') as f:
s = f.read().strip()
for i, j in product(range(10), repeat=2):
try:
bits = '1'*i + s + '1'*j
x = bytes.fromhex(f'{int(bits, 2):x}')
if b'CCTF{' in x:
print(x)
break
except:
pass
| python |
class Solution:
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
row = []
column = []
for i in range(len(matrix)):
for j in range(len(matrix[0])):
... | python |
import pytest
from numpy.testing import assert_array_almost_equal
from Auto import *
class Test_AutoSample:
@classmethod
def setup_method(cls):
np.random.seed(123)
cls.target = lambda x: np.where(x < 0, 0, np.exp(-x))
cls.shape = (1,)
cls.njobs = 1
cls.algo = AutoSampl... | python |
#!python
# This generates a java source file by taking each method that has a
# parameters (String s, int off, int end) and generating a copy that
# takes (char[] s, int off, int end).
# Fix emacs syntax highlighting "
src = r"""
// Copyright (C) 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 ... | python |
def print_me(y):
return 10 + y # pragma: no cover
def return_val(val):
val += 1
return val
def return_val2(val):
val += 1
return val
| python |
"""
endpoint schemas for knoweng
"""
| python |
"""Integration tests for dice_roller.py"""
import unittest
import dice_roller
class DiceRollerIntegrationTests(unittest.TestCase):
"""
Integration tests for DiceRoller that check that history() and clear() are working
"""
def test_no_history(self):
"""
test that .history() returns {} ... | python |
from presentation.models import Liked, Author
from django.shortcuts import get_object_or_404
from presentation.Serializers.liked_serializer import LikedSerializer
from presentation.Serializers.author_serializer import AuthorSerializer
from rest_framework import viewsets, status
from rest_framework.response import Respo... | python |
import argparse
import sys
import os.path as osp
import os
sys.path.insert(1, osp.abspath(osp.join(os.getcwd(), *('..',)*2)))
from dataset_preprocess import CoraDataset, PlanetoidDataset
from attack.models import *
import torch
import pandas as pd
from tqdm.notebook import tqdm
from attack.GAFNC import GNNAttack
from t... | python |
import sympy
class Curtis:
type = 0
# module for computing zUy and UxU
deodhar = 0
# Bruhat form
bruhat = 0
# the Chevalley group
group = 0
# the Weyl group
weyl = 0
# standard parabolics
para = 0
# distinguished expressions for standard parabolics
dist_expr_p = 0... | python |
from django.http import HttpResponse, Http404
from django.shortcuts import render
from django.template import TemplateDoesNotExist
from django.template.loader import get_template
from django.contrib.auth.views import LoginView
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins imp... | python |
"""Updating max length of s3_name in account table
Revision ID: 1727fb4309d8
Revises: 51170afa2b48
Create Date: 2015-07-06 12:29:48.859104
"""
# revision identifiers, used by Alembic.
revision = '1727fb4309d8'
down_revision = '51170afa2b48'
from alembic import op
import sqlalchemy as sa
def upgrade():
### com... | python |
# criando uma sequencia de fibonacci
# o proximo numero e sempre a soma dos 2 anteriores
print('Seguencia de Finonacci')
print('--'*20)
# pedindo um numero
n = int(input('Quantos termos voce quer mostrar: '))
# primeiro termo
t1 = 0
# segundo termo
t2 = 1
# mostrando os 2 primerios termos
print(f'{t1} -> {t2}', end='')... | python |
from org.transcrypt.stubs.browser import *
import random
array = []
def gen_random_int(number, seed):
my_list = [i for i in range(number)]
random.seed(seed)
random.shuffle(my_list)
result = my_list
return result
def generate():
global array
number = 10
seed = 200
gen_random_int(number, seed... | python |
import math
import random
import itertools
import collections
import numpy as np
def grouper(lst, num):
args = [iter(lst)]*num
out = itertools.zip_longest(*args, fillvalue=None)
out = list(out)
return out
def get_batch(batch_data, config, rot='_rot'):
"""Given a batch of data, determine the input ... | python |
"""This program searches through an email file and returns the sender email and date of sending """
user_input = input('Enter filename: ')
fhand = open(user_input)
for line in fhand:
line = line.rstrip()
if not line.startswith('From '): continue
words = line.split()
# print(words)
print(words[1:5], w... | python |
import oi
import os
import sys
import logging
from logging.handlers import SysLogHandler
import time
import service
try:
import config
except ImportError:
import example1.config as config
def stop_function():
ctl = oi.CtlProgram('ctl program', config.ctl_url)
ctl.call('stop')
ctl.client.close()
c... | python |
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
METRICS = (
'hazelcast.instance.managed_executor_service.completed_task_count',
'hazelcast.instance.managed_executor_service.is_shutdown',
'hazelcast.instance.managed_executor_service.is_termin... | python |
import time
import webhook_listener
import json
# arduino = serial.Serial(port='COM14', baudrate=115200, timeout=0)
def process_post_request(request, *args, **kwargs):
req = (format(
request.body.read(int(request.headers["Content-Length"]))
if int(request.headers.get("Content-Length", 0)) ... | python |
#!/bin/env python
#
# Copyright 2013-2014 Graham McVicker and Bryce van de Geijn
#
# 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 ... | python |
#!/bin/python
# -*- coding: utf-8 -*-
import requests
CITY = "787657"
API_KEY = "yourapikey(can be registered on openweathermap.org)"
UNITS = "Metric"
LANG = "en"
REQ = requests.get("http://api.openweathermap.org/data/2.5/weather?id={}&lang={}&appid={}&units={}".format(CITY, LANG, API_KEY, UNITS))
try:
if REQ.s... | python |
#Build In
import os
import sys
import pickle
import copy
import random
# Installed
import numpy as np
from scipy.spatial.transform import Rotation as R
from pathlib import Path
import torch
import spconv
from argoverse.data_loading.argoverse_tracking_loader import ArgoverseTrackingLoader
# Local
from pcdet.utils impo... | python |
import pytest
from app.core.enums import CaseStatus
from app.entities import RecordOnAppeal, Court
def test_roa_from_district_case(simple_case) -> None:
'''
It should create an record of appeal for this case, set the original_case_id.
'''
court = Court.from_id('ca9')
roa = simple_case.create_recor... | python |
import asyncio
# 获取事件循环
import time
loop = asyncio.get_event_loop()
async def main():
await asyncio.sleep(10)
print("main coroutine running")
print(time.time_ns())
# 运行一个协程函数
loop.run_until_complete(main())
print(time.time_ns())
# 在线程池中运行一个协程函数
# loop.run_in_executor()
# 运行一个事件循环
loop.run_forever() | python |
"""
ga2vcf cli
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import ga4gh.converters.cli as cli
import ga4gh.converters.converters as converters
import ga4gh.common.cli as common_cli
import ga4gh.client.cli as cli_client
class Ga2VcfRunner(cli_clie... | python |
#MenuTitle: Angularizzle
# -*- coding: utf-8 -*-
__doc__="""
Creates angular versions of glyphs made up of cubic paths.
"""
import math
import vanilla
import copy
import GlyphsApp
f = Glyphs.font
masterlen = len(f.masters)
# Script name by Type Overlord Florian Horatio Runge of Flensborre @FlorianRunge
class Angela(... | python |
from django.contrib import admin
from .models import ContactQuery
# Register your models here.
admin.site.register(ContactQuery)
| python |
######### Third-party software locations #########
hmmer_dir = "./hmmer_linux/bin/"
phobius_dir = "./phobius/"
#these can be overriden by the --hmerdir, --phobiusdir and -wp options
phobius_url = "https://phobius.sbc.su.se/cgi-bin/predict.pl"
######### Profile HMM locations #########
PTKhmm_dir = "./pHMMs/"
JM... | python |
import logging
from quarkchain.evm.slogging import get_logger, configure_logging
"""
slogging module used by ethereum is configured via a comman-separated string,
and each named logger will receive custom level (defaults to INFO)
examples:
':info'
':info,p2p.discovery:debug'
because of the way that configure_logging... | python |
"""
The module opens the camera capture a point cloud and:
- mesh the point cloud and give back a water-tight mesh
"""
import copy
import sys
from tomlkit import key
if sys.version_info[0] == 2: # the tkinter library changed it's name from Python 2 to 3.
import Tkinter
tkinter = Tkinter #I decided to use a... | python |
#
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is 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
#
# THIS SOFTWARE IS PRO... | python |
#!/usr/bin/env python3
# encoding: utf-8
import sys
def trace_calls_and_returns(frame, event, arg):
co = frame.f_code
func_name = co.co_name
if func_name == 'write':
# Ignore write() calls from printing
return
line_no = frame.f_lineno
filename = co.co_filename
if not filename.... | python |
from django.contrib import admin
from .models import Customer
# Register your models here.
admin.site.register(Customer) | python |
"""main API module."""
from __future__ import annotations
import dataclasses
from dataclasses import dataclass
from enum import Enum
from typing import Any, Union, cast
import aiohttp
from siyuanhelper import exceptions
data_type = Union[dict, list, None]
class Siyuan:
"""Siyuan Helper Instance."""
def... | python |
from texthooks.macro_expand import main as macro_expand_main
def test_macro_expand_no_changes(runner):
result = runner(macro_expand_main, "foo")
assert result.exit_code == 0
assert result.file_data == "foo"
def test_macro_expand_simple(runner):
result = runner(macro_expand_main, "f:bar", add_args=["... | python |
from tkinter import Tk, Label, Button, N, E, S, W
def exitMsg(save, dest):
def saveFunc():
save()
exitFunc()
def exitFunc():
dest.destroy()
window.destroy()
window = Tk()
Label(window, text="Do you really want to close this window without saving?").grid(row=0, column=... | python |
"""
=========================================================================
Decoding sensor space data with generalization across time and conditions
=========================================================================
This example runs the analysis described in :footcite:`KingDehaene2014`. It
illustrates how o... | python |
import os
import uuid
from tests.graph_case import GraphTestCase
from office365.graph.onedrive.drive import Drive
from office365.graph.onedrive.driveItem import DriveItem
from office365.graph.onedrive.file_upload import ResumableFileUpload
def create_list_drive(client):
list_info = {
"displayName": "Lib... | python |
#coding:utf-8
import numpy as np
# 2.使用函数创建
# 如果生成一定规则的数据,可以使用NumPy提供的专门函数
# arange函数类似于python的range函数:指定起始值、终止值和步长来创建数组
# 和Python的range类似,arange同样不包括终值;但arange可以生成浮点类型,而range只能是整数类型
np.set_printoptions(linewidth=100, suppress=True)
a = np.arange(1, 10, 0.5)
print('a = ', a)
# linspace函数通过指定起始值、终止值和元素个数来创建数组,缺省包括终止值... | python |
def a1(str):
print(str[::-1])
def a2(str):
list=str.split()
print(" ".join(list[::-1]))
def a3(str):
if str[:(len(str)//2)]==str[(len(str)//2):]:
print("Symmetric")
else:
print("Asymmetric")
def a4(str):
if str==str[::-1]:
print("Palindrome")
else:
... | python |
import os
import glob
import shutil
import tarfile
from pathlib import Path
DESCRIPTION = """
Prifysgol Bangor University
"""
TECHIAITH_RELEASE=os.environ["TECHIAITH_RELEASE"]
#
def copy_for_evaluation_or_publishing(source_dir, target_dir):
Path(target_dir).mkdir(parents=True, exist_ok=True)
# copy ... | python |
def count_substring(string, sub_string):
found = 0
sub_length = len(sub_string)
for index, _ in enumerate(string):
string_slice = string[index:sub_length + index]
# Debug print statement to confirm assumptions about what the slice looks like.
#print(f'Found: {string_slice}')
... | python |
def build_person(first_name, last_name):
"""Return a dictionary of information about a person."""
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
| python |
import sys, os, threading, queue
sys.path.append('.')
os.chdir('..')
import normalize
from singleton import db
num_workers = 64
in_q = queue.Queue()
out_q = queue.Queue()
class Worker(threading.Thread):
def run(self):
while True:
uid, url = in_q.get()
if uid is None:
out_q.put((None, None, N... | python |
import lemma
import re
TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text):
return TAG_RE.sub('', text)
# def lem_parse(data):
# pass
def lem_parse(text,cnt,check,all_ham,all_spam):
content = remove_tags(text)
x,all_ham,all_spam = lemma.data(content,cnt,check,all_ham,all_spam)
return (x,all_ham,al... | python |
#!/usr/bin/env python3
import sys
import os
import argparse
import logging
from traitlets.config import Config
import nbformat
from nbconvert import NotebookExporter
import utils
from clean import clean
CLEAN = 1
# TODO: would be nice to do some Make-like shortcuts to avoid processing notebooks
# whose rendered mti... | python |
# plugin method for deleting files from an archive
# using the linux "find" commmand.
# this only works if you have a configuration
# with a single archive server which is
# defined in the servers dictionary
from plugins.handyrepplugin import HandyRepPlugin
class archive_delete_find(HandyRepPlugin):
# plugin to d... | python |
import os.path
import random
class AutomaticPotato:
def parent_dir(self):
return os.path.dirname(__file__)
def public_dir(self):
pd = self.parent_dir()
return os.path.abspath(os.path.join(pd, '../../public'))
def potatoes(self):
return os.listdir(self.public_dir())
de... | python |
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys
sys.path.append('../')
# End of fix
from NiaPy.algorithms.basic import CuckooSearch
from NiaPy.benchmarks import Sphere
from NiaPy.task import StoppingTask
# we will run Cuckoo... | python |
from zipfile import ZipFile
from os.path import isdir, isfile, expanduser
from os import getcwd, popen
from shutil import rmtree
from threading import Thread
import sys, ctypes, os
import requests
def run_follower_maker(path):
file = "{}\\followerMaker.exe".format(path)
if isfile(file):
print('run in... | python |
lines = open('input.txt', 'r').readlines()
positions = [int(p) for p in lines[0].split(",")]
# part one
costs = 10e20
optimal_height = 0
for height in range(max(positions)):
current_cost = 0
# calculate cost for height
for p in positions:
current_cost += abs(p-height)
# check if the current ... | python |
# pylint: skip-file
# type: ignore
# -*- coding: utf-8 -*-
#
# tests.models.function.function_unit_test.py is part of The RAMSTK Project
#
# All rights reserved.
# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com
"""Test class for testing function module algorithms and models... | python |
from __future__ import annotations
import os
import platform
from typing import Union
from numpy import arange, array, cumsum, dot, ones, vstack
from numpy.linalg import pinv
from numpy.random import Generator, RandomState
from arch.typing import UnitRootTrend
# Storage Location
if platform.system() == "Linux":
... | python |
import json
import requests
from src import env
from src.utils import response_contains_json
CVE_URL = '/api/cve'
cve_id = 'CVE-1999-0001'
update_cve_id = create_cve_id = 'CVE-2000-0008'
#### GET /cve ####
def test_get_all_cves(org_admin_headers):
""" services api rejects requests for admin orgs """
res = re... | python |
"""
Python library for interacting with ACINQ's Strike API for lightning
network payments.
"""
import json
import base64
import http.client
import urllib.parse
import ssl
import abc
import socket
from .exceptions import ConnectionException, ClientRequestException, \
ChargeNotFoundException, UnexpectedResponse... | python |
import uuid
import datetime
from common.database import Database
class Post(object):
# we can have default parameters in the end id=None
def __init__(self, title, content, author, blog_id, created_date=datetime.datetime.utcnow(), _id=None):
# id = post id, blog_id = blog id,
self.title = title... | python |
import npyscreen
class ProcessBar(npyscreen.Slider):
def __init__(self, *args, **keywords):
super(ProcessBar, self).__init__(*args, **keywords)
self.editable = False
class ProcessBarBox(npyscreen.BoxTitle):
_contained_widget = ProcessBar
class TestApp(npyscreen.NPSApp):
... | python |
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
import os.path
import re
import shutil
class UserProfile(models.Model):
user = models.ForeignKey(User, unique = True)
pic = models.ImageField(upload_to = 'profiles')
best_answers = models.I... | python |
#!/usr/bin/env python
import json
import re
import requests
import sys
FOLDER = 'debug' #'analyses'
GENS = ['sm' ] #['rb', 'gs', 'rs', 'dp', 'bw', 'xy', 'sm']
def dexUrl(gen):
return 'https://www.smogon.com/dex/' + gen + '/pokemon'
def setUrl(gen, poke):
return dexUrl(gen) + '/' + poke
for gen in GENS:
dex ... | python |
#coding=utf-8
from sklearn.datasets import load_svmlight_file
from sklearn.datasets import dump_svmlight_file
from sklearn.cluster import AgglomerativeClustering
from sklearn.externals import joblib
hac_model = joblib.load('hac_result.pkl')
tfidf_matrix, y_train = load_svmlight_file("./d_train.txt")
dump_svmlight_... | python |
from glue_utils import InputExample
import sys
import torch
# convert .pth file to .txt file (use for generating adversarial examples in text format)
def create_file(mode):
examples = torch.load(f'{sys.argv[1]}_adv/{mode}-examples.pth')
with open(f'{sys.argv[1]}_adv/{mode}.txt', 'w') as f:
for example ... | python |
"""Instrument sqlite3 to report SQLite queries.
``patch_all`` will automatically patch your sqlite3 connection to make it work.
::
from ddtrace import Pin, patch
import sqlite3
# If not patched yet, you can patch sqlite3 specifically
patch(sqlite3=True)
# This will report a span with the default... | python |
__package__ = "PyUtil_Lib"
__author__ = "Phong Lam"
| python |
# Copyright 2020-2021 Exactpro (Exactpro Systems Limited)
#
# 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... | python |
# pylint: disable=unused-argument
"""Testing Module nlp.pdflib_dcr."""
import os
import cfg.glob
import pytest
import dcr
# -----------------------------------------------------------------------------
# Constants & Globals.
# -----------------------------------------------------------------------------
# pylint: di... | python |
import json
import os
import random
from bonsai_common import SimulatorSession, Schema
import dotenv
from microsoft_bonsai_api.simulator.client import BonsaiClientConfig
from microsoft_bonsai_api.simulator.generated.models import SimulatorInterface
from sim import extrusion_model as em
from sim import units
# time ... | python |
# flake8: noqa pylint: skip-file
"""Tests for the TelldusLive config flow."""
import asyncio
from unittest.mock import Mock, patch
import pytest
from homeassistant import data_entry_flow
from homeassistant.components.tellduslive import (
APPLICATION_NAME, DOMAIN, KEY_SCAN_INTERVAL, SCAN_INTERVAL,
config_flow)... | python |
# 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
# d... | python |
import unittest
from translator import english_to_french, french_to_english
class TestE2F(unittest.TestCase):
def test1(self):
self.assertEqual(english_to_french(""), "API Exception") # test null
self.assertEqual(english_to_french("Hello"), "Bonjour") # test positive
self.assertNotEq... | python |
import errno
import logging
import os
from typing import TYPE_CHECKING, Optional
from .errors import ObjectFormatError
if TYPE_CHECKING:
from dvc.fs.base import FileSystem
from dvc.hash_info import HashInfo
from dvc.types import AnyPath
from .db.base import ObjectDB
logger = logging.getLogger(__name... | python |
"""Generators - Small
=====================
Some small graphs
"""
import pytest
from networkx.generators.tests.test_small import TestGeneratorsSmall
from graphscope.framework.errors import UnimplementedError
from graphscope.nx.utils.compat import with_graphscope_nx_context
@pytest.mark.usefixtures("graphscope_ses... | python |
import random
def bogoSort(a):
while (is_sorted(a)== False):
shuffle(a)
def is_sorted(a):
n = len(a)
for i in range(0, n-1):
if (a[i] > a[i+1] ):
return False
return True
def shuffle(a):
n = len(a)
for i in range (0,n):
r = random.randint... | python |
from alembic import op
import sqlalchemy as sa
"""add ride resync date
Revision ID: 21518d40552c
Revises: d4be89cbab08
Create Date: 2020-02-01 08:53:33.632416
"""
# revision identifiers, used by Alembic.
revision = '21518d40552c'
down_revision = 'd4be89cbab08'
def upgrade():
op.add_column('rides', sa.Column('... | python |
from flask import Flask, render_template, request
from wtforms import Form, DecimalField, validators
app = Flask(__name__)
class EntryForm(Form):
x_entry = DecimalField('x:',
places=10,
validators=[validators.NumberRange(-1e10, 1e10)])
y_entry = DecimalFi... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.