text stringlengths 3.07k 12.6k |
|---|
'''
Extended Euclidean algorithms for testing.
'''
import random
from typing import Tuple
def decompose(n: int) -> Tuple[int, int]:
'''
Citation: https://jeremykun.com/2013/06/16/miller-rabin-primality-test/
Citation: https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
'''
exponentOf... |
from flask import jsonify, Blueprint, request, g
from app.common.decorator import jwt_role
from app.models import *
from app.common.helper import *
tcase = Blueprint("tcase", __name__)
@tcase.route('/tcase/<object_id>', methods=['GET'])
@jwt_role()
def tcase_details(object_id):
_model = get_model(TestCase, ob... |
import itertools
import pytest
from pdm.exceptions import NoVersionsAvailable, ResolutionImpossible
from pdm.models.candidates import identify
from pdm.models.requirements import parse_requirement
from pdm.models.specifiers import PySpecSet
from pdm.resolver import (
BaseProvider,
EagerUpdateProvider,
Reu... |
import csv
import pandas as pd
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
ps = PorterStemmer()
#stop words in english lanugage
stop_words = set(stopwords.words('english'))
def read_csv_file(... |
# coding=utf-8
# Copyright 2018 The Google AI Team 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 applicabl... |
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from collections import deque
from random import randint
from typing import List, Union, Optional
class Splash(QWidget):
def __init__(self):
super().__init__()
# create model
self.model = TableItemModel(se... |
# -*- coding: utf-8 -*-
"""
This file contains all jobs that are used in tests. Each of these test
fixtures has a slighty different characteristics.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import time
import signal
import sys
import su... |
# Things that would be nice:
# - less hard-coding of paths here
import argparse
import copy
import errno
import json
import os.path
import socket
import subprocess
import sys
import time
from typing import Dict, List, Tuple
PORT = 8642
CLIENT_CONFIG = {
"options": {"failByDrop": False},
"outdir": "./reports/... |
import matplotlib.pyplot as plt
# from sklearn import metrics
from sklearn.metrics import roc_curve, auc, confusion_matrix
from sklearn import preprocessing
import tensorflow as tf
import pandas as pd
import numpy as np
import pickle
import matplotlib.pyplot as plt
def compute_rates(y_test, y_pred, pos_label=1):... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright by affggh
# This program based on Apache 2.0 LICENES
import os
AUTHOR = "affggh"
LICENES = "Apache 2.0"
VERSION = "1.0"
def scanfs(file): # 读取fs_config文件返回一个字典
fsfile = open(file, "r")
fsconfig = {}
for i in fsfile.readlines():
... |
import argparse
import os
import shutil
import multiprocessing
import numpy as np
from PIL import Image
from joblib import Parallel, delayed
from sklearn.metrics import average_precision_score
import torch
def restricted_float(x, inter):
x = float(x)
if x < inter[0] or x > inter[1]:
raise argparse.Ar... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
"""
GPTuner is a Bayesian Optimization method where Gaussian Process is used for modeling loss functions.
See :class:`GPTuner` for details.
"""
import warnings
import logging
import numpy as np
from schema import Schema, Optional
from sklearn.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 20 22:08:02 2021
@author: dhulls
"""
from os import sys
import os
import pathlib
import numpy as np
import random
from scipy.stats import lognorm
from scipy.stats import norm
from scipy.stats import rayleigh
from scipy.stats import uniform
from sci... |
from audiomate.corpus import assets
from audiomate.utils import textfile
WILDCARD_COMBINATION = ('**',)
class UnmappedLabelsException(Exception):
def __init__(self, message):
super(Exception, self).__init__(message)
self.message = message
def relabel(label_list, projections):
"""
Relabe... |
import torch
from torch import nn
import torchvision.models as models
from transformers import *
from .frozen_batch_norm import FrozenBatchNorm2d
LANG_MODELS = {
'bert': (BertModel, BertTokenizer, 'bert-base-uncased'),
'bert-large': (BertModel, BertTokenizer, 'bert-lar... |
import pandas as pd
import os
import numpy as np
SUMMARY_RESULTS='summaryResults/'
NUM_BINS = 100
BITS_IN_BYTE = 8.0
MILLISEC_IN_SEC = 1000.0
M_IN_B = 1000000.0
VIDEO_LEN = 44
K_IN_M = 1000.0
K_IN_B=1000.0
REBUF_P = 4.3
SMOOTH_P = 1
POWER_RANGE= 648 #Difference between max and min avg power
BASE_POWER_XCOVER=1800.... |
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompan... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/DeviceDefinition) on 2019-07-29.
# 2019, SMART Health IT.
import sys
from dataclasses import dataclass
from typing import ClassVar, Optional, List
from .fhirabstractbase import empty_list
f... |
from __future__ import annotations
import curses
import json
import pytest
from testing.runner import and_exit
THEME = json.dumps({
'colors': {'background': '#00d700', 'foreground': '#303030'},
'tokenColors': [
{'scope': 'comment', 'settings': {'foreground': '#767676'}},
{
'scop... |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
import pygame
from pygame import Rect, transform, image
from sheetmusicui.style import colors
from sheetmusicui import notes
class Staff:
"""Staff that manages notes inside it"""
STAFF_LINE_INTERVAL = 30 # Pixel interval between staff lines
STAFF_LINE_PIXEL_WIDTH = 2 # Width in Pixel of staff line
... |
from typing import Optional
import logging
import sys
import pytest
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s test %(levelname)s: %(message)s",
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger("ambassador")
from ambassador import Config, IR
from ambassador.fetch import Resour... |
#
# utils.py
# gw2-discord-webhooks
#
# Copyright (c) 2020 Patrick "p2k" Schneider
#
# 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 th... |
from functools import partial
from numpy import diff
from jax.api import jacfwd
import jax.numpy as jnp
from jax._src.util import safe_map, safe_zip
from jax.flatten_util import ravel_pytree
from jax import linear_util as lu
import jax
from jax import lax
from jax import device_put
map = safe_map
zip = safe_zip
de... |
import tensorflow as tf
class SR4DFlowNet():
def __init__(self, res_increase):
self.res_increase = res_increase
def build_network(self, u, v, w, u_mag, v_mag, w_mag, low_resblock=8, hi_resblock=4, channel_nr=64):
channel_nr = 64
speed = (u ** 2 + v ** 2 + w ** 2) ** 0.5
mag = ... |
from code import interact
import optparse
import sys
import textwrap
from pyramid.compat import configparser
from pyramid.util import DottedNameResolver
from pyramid.paster import bootstrap
from pyramid.paster import setup_logging
from pyramid.scripts.common import parse_vars
def main(argv=sys.argv, quiet=False):
... |
from typing import Union, Callable
import numpy as np
import warnings
import torch
import torch.nn as nn
from sklearn.metrics import f1_score
def setup_evaluator(metric: Union[str, Callable]):
if isinstance(metric, str):
metric = metric.lower()
if metric == "acc" or metric == "accuracy":
... |
import os
from telethon.tl.types import *
from KilluaRobot.utils.pluginhelper import runcmd
async def convert_to_image(event, borg):
lmao = await event.get_reply_message()
if not (
lmao.gif
or lmao.audio
or lmao.voice
or lmao.video
or lmao.video_note
or lmao.p... |
#! /usr/bin/env python3
# Adapted from http://kitchingroup.cheme.cmu.edu/blog/2013/02/18/Nonlinear-curve-fitting/
import glob
import numpy as np # type: ignore
import pandas as pd # type: ignore
from scipy.optimize import leastsq # type: ignore
import argparse
import warnings
warnings.filterwarnings("ignore", cat... |
import os
import sys
import json
import shutil
import pickle
import logging
import data_helper
import numpy as np
import pandas as pd
import tensorflow as tf
from text_cnn_rnn import TextCNNRNN
import warnings
warnings.filterwarnings("ignore")
logging.getLogger().setLevel(logging.INFO)
def load_trained_params(train... |
import random
import numpy as np
import torch
import torch.utils.data
from synthesizer.tacotron2.layers import TacotronSTFT
from synthesizer.tacotron2.utils import load_wav_to_torch, load_filepaths_and_text
from synthesizer.tacotron2.text import text_to_sequence
import os
class TextMelLoader(torch.utils.data.Dataset... |
import os
import sys
import importlib
import logging
import time
import argparse
from uuid import uuid1
import pickle
import platform, multiprocessing
import random
sys.path.append("../")
from gobigger.server import Server
from gobigger.render import RealtimeRender, RealtimePartialRender, EnvRender
from gobigger.agent... |
import cv2
import constants
import numpy as np
from geometry_msgs.msg import Point
def pixels_2_mm(pt_px):
x = (pt_px.x - constants.ORIGIN_PIXELS.x) * constants.COVERT_PIXEL2MM
y = -1 * ((pt_px.y - constants.ORIGIN_PIXELS.y) * constants.COVERT_PIXEL2MM)
z = (constants.ORIGIN_PIXELS.z - pt_px.z) * constant... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 7 18:34:54 2019
@author: ym
"""
import numpy as np
import torch.nn as nn
import Blockmodule as bm
import SEmodule as se
import torch.nn.functional as F
import torch
import pdb
params = {'num_channels' : 1,
'num_filters' : 64,
'kern... |
""" Player classes """
import random
from abc import ABC, abstractmethod
from operator import itemgetter
from random import Random
from typing import Optional, Dict
import numpy as np
import tensorflow as tf
from gym_connect_four import ConnectFourEnv
from losing_connect_four import DeepQNetwork
from losing_connect_... |
"""
Script for generating synthetic data for FactCC training.
Script expects source documents in `jsonl` format with each source document
embedded in a separate json object.
Json objects are required to contain `id` and `text` keys.
"""
import argparse
import json
import os
from tqdm import tqdm
import augmentatio... |
""" An assortment of various search algorithms
"""
import time
import random
def validate_numeric_array(lyst):
""" This function makes sure a list holds only numerical values
"""
for num in range(len(lyst)):
if not str(lyst[num]).isdigit():
raise ValueError
return True
def is_... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import json
import requests
import os
from frappe import _
from frappe.model.document import Document
from frappe.frappeclient impor... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
# Copyright © 2020 The vt-py 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/lice... |
# -*- coding: utf-8 -*-
"""
otpauth
~~~~~~~
Implements two-step verification of HOTP/TOTP.
:copyright: (c) 2013 - 2015 by <NAME>.
:license: BSD, see LICENSE for more details.
"""
import sys
import time
import hmac
import base64
import struct
import hashlib
import warnings
if sys.version_info[0] ... |
#
# Copyright (c) 2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
import os
import sys
import math
import pandas as pd
import csv
import pickle
sys.path.append(os.path.join(sys.path[0], 'moduls'))
sys.path.append(os.path.join(sys.path[0], 'data'))
pd.set_option('display.max_rows', 200)
pd.set_option('display.max_columns', 10)
def load_filter():
"""
load default categorie... |
"""Dataset reader for multilabel dataset in arff (MEKA) format.
See `this <http://www.uco.es/kdis/mllresources>`_ for reference."""
from typing import (
Dict,
List,
Any,
Iterator,
cast,
Tuple,
Iterable,
Optional,
)
import sys
import logging
import json
import numpy as np
from allennlp.... |
"""
This module implements the upload and remove endpoints of the profile image api.
"""
import datetime
import itertools
import logging
from contextlib import closing
from django.utils.translation import ugettext as _
from edx_rest_framework_extensions.auth.jwt.authentication import JwtAuthentication
from edx_rest_... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
import numpy as np
from pyglet.gl import *
from vsml import vsml
class Camera(object):
def __init__(self):
pass
def update(self):
" This should update the camera "
pass
def draw(self):
pass
def info(self):
pass
# ideas
# http://code.enthought.com/projects/ma... |
def string_simple_examples():
print(' ')
print('Strings')
print('-----------')
string1 = 'Hello world!'
string2 = "Hello world!"
print(string1)
print(string2)
# multiline strings use triple quotes
lorem_ipsum = '''
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ... |
import pandas as pd
import matplotlib.pyplot as plt
import math
from datetime import timedelta
import seaborn as sns
POPULATION = 5_822_434 # https://en.wikipedia.org/wiki/Wisconsin
JNJ = {
"2021-03-22": 43_057, # This is when they started publishing manufacturer
"2021-03-25": 51_190,
"2021-03-27": 53_72... |
# Copyright (C) 2006 <NAME>, Science and Technology Facilities Council,
# Daresbury Laboratory.
# All rights reserved.
#
# Developed by: <NAME>
# Science and Technology Facilities Council
# Daresbury Laboratory
# Computational Science and Engineering... |
from django.contrib.auth import get_user_model
from graphene import relay, ObjectType
from graphene_django.filter import DjangoFilterConnectionField
import django_filters
import graphene
import graphql_jwt
from graphene_django import DjangoObjectType
from profiles_api.models import ProfileImage, ProfileDetails
from gra... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 1 16:32:17 2017
@author: andre
"""
import pandas as pd
def LEC_global(location,ntavg):
"""
reads gloabl integral output from LEC.f90
returns pandas dataframe time series
"""
if ntavg==5:
start_year=278
end_year = 325
for t i... |
### Preamble ###################################################################
#
# Author : <NAME>
#
# Github : https://github.com/maxcollins1999
#
# Title : utils.py
#
# Date Last Modified: 17/12/2019
#
# Notes : Contains the generic functions that are used by
# ... |
"""
An easy way to tile windows, specifying the location, number of rows, and
number of columns.
Throughout the script, these variables are used as defined:
location: [row, column] position from top to bottom and left to right
rows: the number of total rows
columns: the number of total columns
padding:... |
import argparse
import os
import time
import shutil
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
from random import sample
import numpy as np
from torch.opti... |
from microbit import *
import random
import radio
ROCKS_ID = 'mtr'
my_id = None
player_num = None
players = []
def start_up_screen():
"""Display the start up screen"""
display.show(Image.ALL_CLOCKS, delay=150, loop=False, clear=True)
return
def display_winner():
print("game over " + str(player_nu... |
# MVPD - Neural Network Model
import os
import importlib
import nibabel as nib
import numpy as np
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.autograd import Variable
from mvpd.dataloader.loader_neural_net import ROI... |
""" A simple agent-environment training loop. """
import operator
import time
from typing import Optional
from acme import core
from acme.utils import counting
from acme.utils import loggers
import dm_env
from dm_env import specs
import numpy as np
import tree
from collections import deque
from qdeep.utils.utils imp... |
"""Tools for relational data"""
# Copyright (c) 2017 <NAME>. This is free software released
# under the MIT License. See `LICENSE.txt` for details.
import itertools as itools
import operator
from .records import RecordStream
from .collections import NamedItems
class Relations(NamedItems):
"""A collection of... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
... |
import autograd.numpy as np
from autograd import grad
import scipy as sc
from scipy import optimize
from scipy import stats
import copy
EXP_MAX = 700.0
EXP_MIN = -700.0
class Policy:
def __init__(self, act_dim, cov0):
self.act_dim = act_dim
self.mu = np.random.randn(self.act_dim)
self... |
import click
import pandas
import json
from clients import s3, redis
@click.command()
@click.option('--both', 'upload', flag_value='s3_and_redis', default=True, help='Upload metadata to both s3 and Redis')
@click.option('--s3', 'upload', flag_value='only_s3', help='Upload metadata only to s3')
@click.option('--redis'... |
# -*- coding: utf-8 -*-
import logging
from collections import deque
import sys
import clipl.utility.logger as logger
log = logging.getLogger(__name__)
import ROOT
import clipl.analysisbase as analysisbase
class HistogramGroupIterator(object):
SKIP_NONE = 0
SKIP_ANY = 1
SKIP_LEADING = 2
SKIP_TRAILING = 4
SKIP... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import caffe
import os
import argparse
import moxing as mox
import shutil
# get current running path
PWD = os.getcwd()
PYTHONPATH = os.environ.get('PYTHONPATH', './').split(':')
# find caffe path
for line in PYTHONPATH:
if 'caffe' in line:
CAFFE_PATH = line[:-7]
... |
import os
import shutil
import glob
import pdf2image
from lxml import etree
# extract pdf to image
def extract_image_from_pdf(filepath, workspace_output_dir):
working_dir = os.path.join(workspace_output_dir, 'images')
image_filename = os.path.splitext(os.path.basename(filepath))[0]
create_directory(wo... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
"""
This module is about path resolving for the skin path.
This is particular useful if you for example try create new skins
or open an existing one.
"""
import getpass
import io
import os
import platform
import re
from functools import lru_cache
import winreg
import sublime
from .. import logger
from .program_pat... |
#!/usr/bin/env python
# coding: utf-8
# Author: <NAME>
from __future__ import print_function, division, absolute_import
import numpy as np
import argparse
import sys
from sys import exit, stdin
from Fred2.Core import Allele, Peptide, Protein,generate_peptides_from_proteins
from Fred2.IO import read_lines, read_fasta... |
from vergeml.io import Sample
from vergeml.utils import SPLITS
import operator
from functools import reduce
from vergeml.cache import MemoryCache, SerializedFileCache
import io
import os.path
class Loader:
def __init__(self, cache_dir, input, ops=None, output=None, progress_callback=lambda n, t: None):
se... |
"""
Copyright (c) 2017, <NAME>.
Distributed under the terms of the GPL v3 License.
The full license is in the file LICENSE, distributed with this software.
Created on Dec 6, 2017
@author: jrm
"""
import os
import json
import enaml
import traceback
import jsonpickle as pickle
from atom.api import (
Atom, Unicode... |
# Copyright (c) Facebook, Inc. and its affiliates.
import os
import imageio
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision.transforms as transforms
from inhandpy.thirdparty.pix2pix.options.test_options import TestOptions
from inhandpy.thirdparty.pix2... |
#!env python3
# -*- coding: UTF-8 -*-
import sys
import plotly.graph_objects as go
import plotly.offline as py
fps = 120
total_log = ''
def sprintf(str_value):
global total_log
total_log += str_value + '\n'
def ReadFile(fichier_html_graphs, file_path):
f = open(file_path, 'r')
total_values = []
... |
"""
Module that provides classes for tree creation and handling.
Trees are powerful structures to sort a huge amount of data and to speed up
performing query requests on them significantly.
"""
from collections import Iterable
import pandas as pd
import numba
import numpy as np
from sklearn.neighbors import BallTre... |
# Copyright (c) 2018 Uber Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
import os, tarfile
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from sklearn.base import BaseEstimator, TransformerMixin
from python_common.global_param import GlobalParam
from urllib import request
from sklearn.impute import SimpleImputer
from sklearn.preproc... |
# Author: <NAME>
"""Hindley-Milner type inference algorithm."""
from kernel.type import HOLType, TVar, TFun
from kernel.term import Term
from kernel import term
from util import unionfind
class TypeInferenceException(Exception):
def __init__(self, err):
self.str = str
def is_internal_type(T):
"""W... |
import json
import os
import random
import requests
from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor, as_completed
import argparse
import pandas as pd
import pdb
from PIL import Image
from io import BytesIO
import sys
import hashlib
import base64
import urllib3
import math
import... |
import logging
import numpy as np
import pyvista
import treefiles as tf
from MeshObject import Mesh
from FractalTree.generator import PurkinjeGenerator
from FractalTree.network import PurkinjeNetwork
@tf.timer
def generate(root):
gen = PurkinjeGenerator(root)
m = Mesh.load(root.surf)
# m.triangulate(m.m... |
import pandas as pd
import bcrypt
# Storing the path of Database.csv in a variable.
filepath_const = r"D:\BasicDatabaseProject\Database.csv"
# Storing the database file in a pandas dataframe df.
df = pd.read_csv(filepath_const)
# We will need a list of all the usernames.
username_list = df["Username"].tolist()
... |
# Lint as: python3
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
import pandas as pd
from pandas import Series,DataFrame
pd.set_option("precision",10)
def part1_pat2_concat():
parti_che_dis = pd.read_csv("original resource/part-i-chemical-disease-path-theme-distributions.txt",
delimiter="\t")
print("done")
parti_che_dis.rename(colum... |
import pygame
import sys
from random import randint,random
SCREEN_WIDTH, SCREEN_HEIGHT = 1024, 768
# The definition of class CLS_disk
class CLS_disk(object):
group = []
def __init__(self, rect, color, speedX, speedY):
self.rect = pygame.Rect(rect)
self.color = color
self.speedX, self.spe... |
import json
from datetime import datetime
from typing import (
Optional,
List,
Dict,
Any,
Tuple,
Callable,
TypeVar,
Set,
)
from pathlib import Path
from .exceptions import URLCacheException
from .common import Json
from .model import Summary
from .dir_cache import DirCache
T = TypeVar... |
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from rest_framework import status
from rest_framework.parsers import MultiPartParser, FormPars... |
import argparse
def _add_common_args(arg_parser):
"""
常规参数
:param arg_parser:
:type arg_parser:
:return:
:rtype:
"""
arg_parser.add_argument('--config', type=str, help="指定配置文件")
# Input
arg_parser.add_argument('--types_path', type=str, help="通往类型规格的路径")
# Preprocessing
... |
# -*- coding: utf-8 -*-
import random
import numpy as np
# # Figure 18-1 on page 396
def roll_die():
return random.choice([1,2,3,4,5,6])
# #Used later in chapter
# def roll_die():
# return random.choice([1,1,2,3,3,4,4,5,5,5,6,6])
def check_pascal(num_trials):
"""Assumes num_trials is an int > 0
P... |
"""Utilities for e2e tests of KubeRay/Ray integration.
For consistency, all K8s interactions use kubectl through subprocess calls.
"""
import logging
from pathlib import Path
import subprocess
import time
from typing import Any, Dict, List, Optional
import yaml
logger = logging.getLogger(__name__)
def wait_for_crd(c... |
#!/usr/bin/python
# @lint-avoid-python-3-compatibility-imports
#
# funcinterval Time interval between the same function, tracepoint
# as a histogram.
#
# USAGE: funcinterval [-h] [-p PID] [-i INTERVAL] [-T] [-u] [-m] [-v] pattern
#
# Run "funcinterval -h" for full usage.
#
# Copyright (c) 2020 Realtek,... |
#!/usr/local/bin/python3
## Author: CaptainSmiley
## Date: 2/18/2021
## License: Creative Commons Zero v1.0 Universal
from ShazamAPI import Shazam
import eyed3
import urllib.request
import subprocess
import sys
import ssl
import os
from os import walk
import getopt
issues = ""
def get_album_image(imageur... |
'''
Code adapted from: https://github.com/ssudholt/phocnet
'''
import logging
import numpy as np
import pdb
def get_most_common_n_grams(words, num_results=50, n=2):
'''
Calculates the 50 (default) most common bigrams (default) from a
list of pages, where each page is a list of WordData objects.
Args:
... |
#!/usr/bin/env python3
"""
@author: <NAME>
@version: 1.0.0
zumi_config_builder.py
Must include yaml representer to preserve order
zUMI requires all paths to be absolute; will need to take this into account
for creating the barcode text file and trimmed fastq samples
"""
from collections import OrderedDict
import ya... |
"""Command line conversion tools `jupytext` and `nbsrc`
"""
import os
import sys
import argparse
from .jupytext import readf, reads, writef, writes
from .formats import NOTEBOOK_EXTENSIONS, JUPYTEXT_FORMATS, \
check_file_version, one_format_as_string, parse_one_format
from .combine import combine_inputs_with_outpu... |
import re
import pandas as pd
PRECEDING_DICT = ['number','numbers','digit','digits','integer','integers','consecutive']
def number_mapper(txt, eq_num_list):
new_str = text2int(txt.lower())
num_list = re.findall(r'[0-9/]+', new_str)
var_list = []
new_str = re.sub(r'[0-9/]+', '$N', new_str)
original... |
import random
import logging
import pathlib
from .Q import Q, EligibilityTrace
from .config import config
base_path = pathlib.Path("comgames/Q")
agent_list = {}
def push(cls):
agent_list[cls.__name__] = cls
return cls
class Agent:
def __init__(self, env, new=False):
self.logger = logging.getL... |
try:
if platform.system() == "Windows":
colorama.init()
except ImportError:
print("Could not init terminal features.")
sys.stdout.flush()
pass
if sys.version_info < (3, 3):
class TimeoutError(Exception):
pass
else:
TimeoutError = TimeoutError
def get_serial_number_str(device):
if hasattr(device, "serial_numb... |
import re
from ryven.NWENV import *
from qtpy.QtGui import QFont
from qtpy.QtCore import Qt, Signal, QEvent
from qtpy.QtWidgets import QPushButton, QComboBox, QSlider, QTextEdit, QPlainTextEdit, QWidget, QVBoxLayout, QLineEdit
class ButtonNode_MainWidget(QPushButton, MWB):
def __init__(self, params):
M... |
# imports from Coopihc
from pointing.envs import SimplePointingTask
from pointing.users import CarefulPointer
from pointing.assistants import ConstantCDGain
from coopihc.policy import BasePolicy, RLPolicy
import coopihc
from coopihc.bundle import PlayUser, PlayNone, Train
# other imports
from collections import Ordere... |
# generic imports
from copy import deepcopy
from shutil import which, copyfile
from pathlib import Path
# AHA imports
import fault
from fault.subprocess_run import subprocess_run
# svreal imports
from svreal import (get_hard_float_sources, get_hard_float_inc_dirs,
get_hard_float_headers, get_svrea... |
#!/usr/local/bin/python3
import sys
import os
from typing import Optional
import docopt
def _using_python2():
return sys.version_info < (3, 0)
# This code does not support Python 2
assert not _using_python2(), 'You are using Python 2 which is not supported. Use Python 3.'
try:
# This works when the code ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted.
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANT... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.