content stringlengths 5 1.05M |
|---|
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
"""
syntax_abbrev.py - Abbreviations for pretty-printing syntax.asdl.
"""
from _devbuild.gen.id_kind_asdl import Id
from asdl import runtime
def _AbbreviateToken(tok, out):
# type: (token, List[runtime._PrettyBase]) -> None
if tok.id != Id.Lit_Chars:
n1 = runtime.PrettyLeaf(tok.id.name, runtime.Color_OtherCo... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/datastore/v1beta3/datastore.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2018 Jun.
@author: HuangLiPang, QuenLo
python version: 2.7
logging config doc:
https://docs.python.org/2/library/logging.config.html
"""
import logging
import logging.config
import time
from RotatingFileNameHandler import RotatingFileNameHandler
class UTCFo... |
'''
Created on Oct 22, 2010
@author: Stephen O'Hara
'''
# PyVision License
#
# Copyright (c) 2006-2008 Stephen O'Hara
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of s... |
"""represents an ipwhois info"""
# -*- coding:utf-8 -*-
import threading
from commonbaby.countrycodes import ALL_COUNTRIES
from datacontract.iscoutdataset.iscouttask import IscoutTask
class IPWhoisEntityData(object):
"""represents an entity in an ipwhois info"""
_roles_def: list = [
"registrant",... |
import enum
class Level(enum.Enum):
CRITICAL = 70
DEBUG = 40
ERROR = 60
FATAL = 80
INFO = 30
NOTICE = 20
TRACE = 10
WARNING = 50
UNSET = 0
class LevelColors(str, enum.Enum):
CRITICAL = "\x1b[38;5;196m"
DEBUG = "\x1b[38;5;32m"
ERROR = "\x1b[38;5;202m"
FATAL = "\x1b... |
from tqdm import tqdm
import tensorflow as tf
# from core.dataset import Dataset
# yolo_data = Dataset('type')
# pbar_yolo = tqdm(yolo_data)
# for batch_data in pbar_yolo:
# continue
# #print(batch_data[0].shape)
## "./data/images/train.txt"
from core.lyhdata import Dataset
yolo_train_data = Dataset('tr... |
import plotly.graph_objects as go
from numpy import arange, sqrt, abs, max, linspace, isnan, histogram, zeros, corrcoef, ceil
from .utils import to_div
from ..utils import get_color_for_val
from ..parameters import FINGERS
def plot_ols_params(df, param, region_type, yaxis_name=''):
SUMMARY = {}
for region... |
import pygame
from pygame import Rect
import config
"""convenience component offsets for tuple coordinates"""
X = 0
Y = 1
class Vehicle:
"""
Represents a truck, car, log, turtle or other moving object
"""
def __init__(self, spec, position, speed) -> None:
super().__init__()
self.spec... |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import re
import jsbeautifier
import js2py
import requests
from copy import deepcopy
import time
from pyquery import PyQuery... |
# -*- coding: utf-8 -*-
"""
@Time: 2021/8/2 16:52
@Author: zzhang [email protected]
@File: omnis_monitor.py
@desc:
"""
from collect.service_imp.flow.omnis_flow import ServiceOmnisFlowService
from collect.utils.collect_utils import get_safe_data, get_key
class ServiceFlowService(ServiceOmnisFlowService):
sf_cons... |
"""Initializes the mongodb database"""
from whist.server.const import DATABASE_NAME
from whist.server.database.connection import get_database
db = get_database(DATABASE_NAME)
|
#
# Copyright (C) 2016 Codethink 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 applicable law or agre... |
# This is an importable rather than a standalone html file
# for a couple of reasons, not least of those being
# than as soon as we take the step toward using file system
# resources, it makes packaging more complex ...
# The other reasons can be summarized as "laziness".
FIRELOGGER_HREF = "https://addons.mozilla.org... |
from flask import Flask
APP_VERSION = "0.0.1"
app = Flask(__name__)
@app.route("/")
def home():
return ""
@app.route("/ping")
def ping():
return {
"version": APP_VERSION
}
if __name__ == "__main__":
app.run()
|
import pickle, os
from PyQt4 import QtGui, QtCore
class Settings():
SETTINGS_FILE = None
THEME_DIR = None
def __init__(self):
self.__theme = '-'
self.__animation_duration = 500
self.__is_fulscreen = False
self.__full_deck = False
self.load()
self.load_reso... |
VALUE = 1 / 0
|
import numpy as np
def rotx(theta):
rot = np.array([[1.0, 0, 0], [0, 1, 0], [0, 0, 1]])
rot[1, 1] = np.cos(theta)
rot[2, 1] = np.sin(theta)
rot[1, 2] = -np.sin(theta)
rot[2, 2] = np.cos(theta)
return rot
def roty(theta):
rot = np.array([[1.0, 0, 0], [0, 1, 0], [0, 0, 1]])
... |
# 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.
#----------------------------------------------------------------------... |
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
__version_info__ = ('0', '0', '6')
__version__ = '.'.join(__version_info__)
name = "revops"
|
import os
# DATABASE SETTINGS
SQLALCHEMY_DATABASE_URI = 'sqlite:////{}/laborapp.db'.format(os.getcwd())
SECRET_KEY = "withgreatpowercomesgreatresponsibility"
DEBUG = True
# mail settings
MAIL_SERVER = 'smtp.example.com'
MAIL_PORT = 465
MAIL_USE_SSL = True
MAIL_USERNAME = 'username'
MAIL_PASSWORD = 'password'
# Fla... |
#!/usr/bin/env python
from time import strftime, gmtime
def now():
return strftime('%Y-%m-%d %H:%M:%S', gmtime())
def number(value):
return float(value.replace('lei', '').replace('.', '').replace(',', '.'))
|
"""Tests for the math.klobuchar-module
"""
from midgard.ionosphere import klobuchar
def test_klobuchar():
# Comparison are done against GPS-Toolbox Klobuchar programs from Ola Ovstedal
# https://www.ngs.noaa.gov/gps-toolbox/ovstedal.htm
t = 593100
ion_coeffs = [
0.382e-07,
0.149e-07,
... |
#!/usr/bin/env python
from pandas import DataFrame, concat, melt, Series
import re
from numpy import where
from collections import OrderedDict
from itertools import chain
__all__ = [
'string_to_list', 'strip_time', 'year_strip', 'extract',
'check_int', 'produce_null_df', 'check_registration',
'UniqueRepla... |
# encoding: utf-8
# module System.Windows.Documents calls itself Documents
# from PresentationFramework,Version=4.0.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35,PresentationCore,Version=4.0.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35
# by generator 1.145
# no doc
# no imports
# no functions
# cl... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, re
def getClassesDict():
f = open('hindiclasses.sorted.txt')
classesDict = dict()
for line in f:
fields = line.split()
classesDict[fields[0]] = fields[1]
f.close()
return classesDict
def renderExample(example):
label = exa... |
from os import sep
import re
import sys
import logging
import numpy as np
import pandas as pd
from dvc import api
from io import StringIO
import warnings
warnings.filterwarnings('ignore')
logging.basicConfig(
format='%(asctime)s %(levelname)s:%(name)s: %(message)s',
level=logging.INFO,
datefmt='%H:%M:%S... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import numpy as np
import time
import open3d as o3d
import misc3d as m3d
""" numpy implementation of farthest point sampling """
def farthest_point_sampling_numpy(xyz, npoint):
N = xyz.shape[0]
indices = [0] * npoint
distance = np.ones((N,)) * 1e10
farthest ... |
#Modules:
import numpy as np
#Public:
class DataLoader:
'''
Classe responsável por gerenciar a padronização das entradas
das enquentes parciais.
'''
#Constructor
def __init__(
self,
fonte,
paredao
):
self._fonte = fonte
self._paredao_names = par... |
import numpy as np
import scipy as sp
from VyPy import tools
from VyPy.exceptions import EvaluationFailure
from VyPy.tools import atleast_2d
class Inference(object):
def __init__(self,Kernel):
self.Kernel = Kernel
self.Train = Kernel.Train
return
... |
import socket
from typing import Tuple, Optional
from collections import deque
from net_test_tools.dataset import preprocess
from net_test_tools.transceiver import Transceiver
from net_test_tools.utils import Multiset, hex_str
def receive_for_dataset(
local: Tuple[str, int],
remote: Optional[Tuple[st... |
import struct
import wtforms
from wtforms.validators import Length, NumberRange
from . import core
class BasicBinaryField(core.BinaryField):
# Some BinaryFields will have inherent value restrictions, based on the
# limitations of the serialized form. For example, a UInt8Field cannot
# store numbers abov... |
print('''
Error #404
Subscribe to my telegram channel @libernet_15''')
|
import os
import sys
from git import Repo, Actor
import time, datetime
from . import ccc
closeCode = 0
months = {
"[01]": "A",
"[02]": "B",
"[03]": "C",
"[04]": "D",
"[05]": "E",
"[06]": "F",
"[07]": "G",
"[08]": "H",
"[09]": "I",
"[10]": "J",
"[11]": "K",
"[12]": "L"
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutStrings(Koan):
def test_double_quoted_strings_are_strings(self):
#is double quoted properly
string = "Hello, world."
self.assertEqual(True, isinstance(string, str))
def test_single_quoted_strings_are_a... |
from .fileOnAES import *
from .fileOnXOR import *
from .fileOnBase64 import *
from .fileOnBase32 import *
from .fileOnBase16 import *
from .fileOnBlowfish import *
from .fileOnDES import *
from .fileOnDES3 import *
from .fileOnARC2 import *
from .fileOnARC4 import *
__all__ = ['fileOnAES','fileOnXOR','fileOnBase64','f... |
"""Basic Unit testing for example.py"""
import math
from random import randint
import pytest
from example import increment, COLORS
def test_increment():
"""Testing increment function"""
test_value = randint(0, 10)
assert increment(3) == 4
assert increment(-2) == -1
assert increment(2.4) == 3.4
... |
#!/usr/bin/env python3
__author__ = 'Bradley Frank'
import argparse
import json
import logging
import os
import shutil
import subprocess
import sys
import urllib.request
PROJECTS = {
'Mailspring': ['Foundry376', 'Mailspring'],
'VSCodium': ['VSCodium', 'vscodium'],
}
REPO_ROOT_DIR = '/srv/repos'
REPO_COLO = ... |
import os
import os, sys, shutil
sys.path.append('../')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from TrialsOfNeuralVocalRecon.data_processing.convenience_tools import timeStructured
#CDIR = os.path.dirname(os.path.realpath(__file__))
CDIR = 'C:/Users\hoss3301\work\TrialsOfNeuralVocalR... |
"""
bbo.py
Defines bbo
"""
__version__ = '1.0'
__author__ = 'Hugo Chauvary'
__email__ = '[email protected]'
from module import logger
from pyspark.sql import SparkSession
from pyspark.sql.types import Row
from module.data import Data
from module.logger import *
from util.util import get_df_types
from util.util... |
from unittest import TestCase
from moceansdk import RequiredFieldException
from moceansdk.modules.command.mc_object.send_sms import SendSMS
class TestTgSendText(TestCase):
def testParams(self):
params = {
"action": "send-sms",
"from": {
"type": "phone_num",
... |
from userbot.utils import register
@register(outgoing=True, pattern="^.me$")
async def join(e):
if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
await e.edit("I AM OUWNER OF EYE GANG /n/n IF ANY YOUR CHANNEL SO MAKE ME ADMIN IN POST PREMIUM ACCOUNT /n/n MY RULES /n/n * NO SEELING /n... |
import numpy as np
import pandas as pd
from scipy.signal import savgol_filter
from plaster.tools.utils import utils, stats
from plaster.tools.schema import check
def radiometry_histogram_analyzer(sig):
"""
This is a bespoke histogram analyzer for radiometry to extract certain guesses.
Assumptions:
*... |
import json
import requests
import os
import data
# Sends api request
def WarframeAPIRequest():
url = ("https://ws.warframestat.us/pc")
r = requests.get(url)
apidata = r.json()
#Directory of the locally saved worldstate json
basedir = os.path.abspath(os.path.dirname(__file__))
data_json = base... |
from base64 import b64encode
import base64
from typing import Optional
from hashlib import md5
from .utils import ChecksumError
try:
import crcmod
except ImportError:
crcmod = None
class ConsistencyChecker:
def __init__(self):
pass
def update(self, data: bytes):
pass
def valida... |
from unittest import TestCase
from xrpl.models.requests import Fee
class TestRequest(TestCase):
def test_to_dict_includes_method_as_string(self):
tx = Fee()
value = tx.to_dict()["method"]
self.assertEqual(type(value), str)
|
from flask import request, json, Blueprint, g
from ..models.comment import CommentModel, CommentSchema
from .user_view import custom_response
from ..shared.authentication import Auth
comment_api = Blueprint('comment_api', __name__)
comment_schema = CommentSchema()
@comment_api.route('/', methods=['POST'])
@Auth.au... |
binary = ["0111111","0001010","1011101","1001111","1101010","1100111","1110111","0001011","1111111","1101011"]
two2ten =[int(i,2) for i in binary]
def f(S):
k = 0
for i in range(0,len(S),3):
t = int(S[i:i+3])
k *=10
k += two2ten.index(t)
return k
while True:
a=input()
if a ==... |
'''
Created on 2022-01-24
@author: wf
'''
import unittest
from tests.basetest import BaseTest
from osprojects.osproject import OsProject, Commit, Ticket, main, GitHub, gitlog2wiki
class TestOsProject(BaseTest):
'''
test the OsProject concepts
'''
def testOsProject(self):
'''
tests i... |
from itertools import permutations
class Solution:
def nextGreaterElement(self, n: int) -> int:
"""
Personal attempt
Space : O(n)
Time : O(n!)
"""
if n < 10:
return -1
a = list(str(n))
ans = -1
perms = permutations(a)
... |
from context import CommandContext
from command import Command
from new import NewCommand
from check import CheckCommand
from gen_ref import GenRefCommand
from resolve import ResolveCommand
from list import ListCommand
from up import UpCommand
from down import DownCommand
from rebuild import RebuildCom... |
"""書籍関連のテスト"""
from django.test import TestCase
from django.core.urlresolvers import reverse
from .factories import BookFactory
class ListViewTests(TestCase):
"""書籍一覧ビューのテスト"""
def setUp(self):
"""前準備"""
self.title = 'テストタイトル'
self.books = BookFactory.create_batch(20, title=self.title... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : RealtimePlotter_test.py
# Author : Duy Anh Pham <[email protected]>
# Date : 23.03.2020
# Last Modified By: Duy Anh Pham <[email protected]>
import unittest
import matplotlib.pyplot as plt
import numpy as np
from Real... |
# Copyright 2019, The TensorFlow 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 agreed t... |
from django.urls import path
from . import views
app_name='app'
urlpatterns = [
path('',views.home,name='home'),
path('upfile_Ajax',views.upfile,name='upfile'),
path('runcmd_Ajax',views.run_cmd,name='run_cmd'),
path('cmd_msg',views.cmd_msg,name='cmd_msg'),
path('file_list',views.file_list,name='file_list'),
path('fi... |
import tensorflow as tf
import grpc
from tensorflow_serving_client.protos import prediction_service_pb2_grpc, predict_pb2
from tensorflow_serving_client.proto_util import copy_message
class TensorflowServingClient(object):
def __init__(self, host, port, cert=None):
self.host = host
self.port = p... |
from .AbstractRepositoryFile import AbstractRepositoryFile
class GitFileInfo(AbstractRepositoryFile):
def __init__(self, workingCopy, status:str, filePath:str):
super().__init__(workingCopy, status, filePath)
#
#
|
import FWCore.ParameterSet.Config as cms
#from HLTrigger.HLTfilters.hltHighLevel_cfi import *
#exoticaMuHLT = hltHighLevel
#Define the HLT path to be used.
#exoticaMuHLT.HLTPaths =['HLT_L1MuOpen']
#exoticaMuHLT.TriggerResultsTag = cms.InputTag("TriggerResults","","HLT8E29")
#Define the HLT quality cut
#exot... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""CLI to log docker stats to a CSV file."""
import argparse
import datetime
import os
import re
import subprocess
import time
HEADER = "name,cpu_percent,mem,mem_percent,netio,blockio,pids,datetime"
REGEX_SIZE = re.compile(r"(\d+(?:\.\d+)?)([a-zA-Z]+)")
CONVERT_MAP = {
... |
"""
The :mod:`expert.utils.conv` module holds util functions for convolutions, like
padding to maintain the size of the image.
"""
# Author: Alex Hepburn <[email protected]>
# License: new BSD
from typing import List
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = ['pad']
def ... |
from typing import Any, List, Union
import pytest
from .parser import AST, ParseError, parse
StrAST = List[Union[str, List[Any]]]
def to_string(ast: AST) -> StrAST:
str_ast: StrAST = []
for node in ast:
if isinstance(node, list):
str_ast.append(to_string(node))
else:
... |
# -*- coding: utf-8 -*-
#
# This file is part of Radicale Server - Calendar Server
# Copyright © 2011-2013 Guillaume Ayoub
#
# This library 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 3 of t... |
from detecting.models.backbones import VGG16,resnet_v1_50,resnet_v1_101,resnet_v1_152
from detecting.utils import model_util
from tensorflow.keras.models import Model
# 选择不同的backbone
def get_backbone(cfg):
if cfg.MODEL.BACKBONE=='vgg16':
return backbone_vgg16(cfg)
elif cfg.MODEL.BACKBONE=='resnet50':
... |
#!/usr/bin/python3
from config import *
import discord
from discord.ext import commands
import json
import os
bot = commands.Bot(command_prefix=prefix)
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
try:
bot.run(token)
except Exception a... |
import json
from sys import exit
names_2 = []
names_3 = []
hobs = []
my_list = ['Имена', 'Фамилии', 'Отчества', 'Увлечения']
list_list = [[],[],[]]
with open('users.csv', 'r', encoding='utf-8') as f_1:
with open('hobby.csv', 'r', encoding='utf-8') as f_2:
if sum(1 for i in f_2) > sum(1 for j in f_1):
... |
from argo.core.hooks.EveryNEpochsTFModelHook import EveryNEpochsTFModelHook
# get_samples_from_dataset
from datasets.Dataset import check_dataset_keys_not_loop, VALIDATION,TEST
from argo.core.argoLogging import get_logger
from matplotlib import pyplot as plt
import tensorflow as tf
import numpy as np
# from matplotlib.... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return No... |
from .model import HighResNet3D
|
from django.contrib import admin
from .models import Photo, PhotoMetaData
class PhotoMetaDataInline (admin.StackedInline):
model = PhotoMetaData
class PhotoAdmin (admin.ModelAdmin):
list_display = ['__str__', 'upload_date', 'marker']
inlines = [PhotoMetaDataInline]
admin.site.register(Photo, PhotoAdmin)
|
import math
import pyorama
from pyorama import app
from pyorama.asset import *
from pyorama.core import *
from pyorama.event import *
from pyorama.graphics import *
from pyorama.math import *
def on_window_event(event, *args, **kwargs):
if event["sub_type"] == WINDOW_EVENT_TYPE_CLOSE:
app.trig... |
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
import requests
import shutil
def s... |
#!/usr/bin/env python
#
# dewadl
#
# Turn WADL XML into Python API.
#
# Matt Kubilus 2015
#
# This is written to support the uDeploy WADL specifically. Your mileage may vary with other WADLs.
#
#
import os
import re
import cmd
import json
import urlparse
import urllib2
from types import FunctionType
import x... |
from pathlib import Path
from django.dispatch import receiver
from django.template import engines
from django.template.backends.django import DjangoTemplates
from django.utils._os import to_path
from django.utils.autoreload import (
autoreload_started,
file_changed,
is_django_path,
)
def get_template_dir... |
# -*- coding: utf-8 -*-
"""
斗地主算法包
"""
from .call_landlord import process
__all__ = ['process']
|
from abc import *
import torch.nn as nn
class DiscriminatorBase(nn.Module,metaclass=ABCMeta):
@abstractmethod
def __init__(self):
super(DiscriminatorBase, self).__init__()
@abstractmethod
def forward(self,x):
pass
@abstractmethod
def get_reward(self):
pass
@abstractme... |
import requests
class Gemini:
def __init__(self, fiat, crypto):
self.url = 'https://api.gemini.com/v1/'
self.fiat = fiat
self.crypto = crypto
self.rate = crypto.lower() + fiat.lower()
self.deposit = 0.00 # EUR
self.fiat_withdrawal = 0.09 # EUR
self.withdraw... |
import re
import pytest
import yapic.di
from yapic.di import Injector, ProvideError, InjectError, __version__
def test_provide_callable():
""" Test only providable callables """
# !!! THIS IS NOT AN EXAMPLE, THIS IS A BAD USAGE, BUT IT CAN WORK IN TEST !!!
injector = Injector()
@injector.provide
... |
from ..dao.event import EventDao
from ..schema.base import ListArgsSchema, RespListSchema, RespIdSchema, RespBaseSchema
class BaseService(object):
"""Base(基础)服务,用于被继承.
CRUD基础服务类,拥有基本方法,可直接继承使用
Attributes:
auth_data: 认证数据,包括用户、权限等
user_id: 当前操作用户id
event_dao: 业务事件dao
dao: ... |
# NG
import os, sys
# OK
import os
import sys
import math
import os
import sys
import Requests
import my_package1
import my_package2
|
# Python-SDL2 : Yet another SDL2 wrapper for Python
#
# * https://github.com/vaiorabbit/python-sdl2
#
# [NOTICE] This is an automatically generated file.
import ctypes
from .api import SDL2_API_NAMES, SDL2_API_ARGS_MAP, SDL2_API_RETVAL_MAP
# Define/Macro
# Enum
SDL_HINT_DEFAULT = 0
SDL_HINT_NORMAL = 1
SDL_HINT_OVERR... |
import pyrosetta.rosetta.core.scoring as scoring
import pyrosetta.toolbox.rcsb as rcsb
import numpy as np
from scipy.stats import wilcoxon
from pyrosetta import *
from jmetal.problem.singleobjective.protein_structure_prediction import ProteinStructurePredictionMultiObjective
if __name__ == '__main__':
problem = ... |
import numpy as np
import operator
# Accuracy from the testing predictions
def getAccuracy(testSet, predictions):
correct = 0
for x in range(len(testSet)):
if testSet[x] == predictions[x]:
correct += 1
return 1.0 * correct / len(testSet)
# A custom distance function for use... |
import lxml.html
from lxml.html.clean import Cleaner
from lxml.cssselect import CSSSelector
cleaner = Cleaner(
scripts=True,
javascript=True,
comments=True,
style=True,
inline_style=True,
links=True,
meta=True,
page_structure=True,
processing_instructions=True,
embedded=True,
... |
from dataclasses import dataclass, field
from typing import Optional
from bindings.csw.actuate_type import ActuateType
from bindings.csw.datum import Datum
from bindings.csw.engineering_datum import EngineeringDatum
from bindings.csw.geodetic_datum import GeodeticDatum
from bindings.csw.image_datum import ImageDatum
fr... |
# encoding: utf-8
import os
from unittest import mock
import pytest
from requests.exceptions import ChunkedEncodingError
from gdcapiwrapper.tcga import Data as TCGAData
from gdcapiwrapper.tcia import Data as TCIAData
from ..mockserver import get_free_port, start_mock_server
class TestTCGAData(object):
@classm... |
import paginate
from flask import request, url_for, render_template, jsonify
from flask.views import MethodView
from flask_login import login_required, current_user
from paginate_sqlalchemy import SqlalchemyOrmWrapper
from sqlalchemy import desc, func
from nanumlectures.common import is_admin_role, paginate_link_tag
f... |
# Order sensitive imports.
from genomic_neuralnet.analyses.optimization_constants \
import DROPOUT, HIDDEN, WEIGHT_DECAY, EPOCHS, RUNS, \
SINGLE_MULTIPLIER, DOUBLE_MULTIPLIER
from genomic_neuralnet.analyses.optimization_result \
import OptimizationResult
from genomic_neura... |
import pandas as pd
import matplotlib.pyplot as plt
raw_data = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/dataset_statistic.csv", sep=';')
plt.clf()
plt.figure()
raw_data[raw_data['Produk'] == 'A'].hist()
plt.tight_layout()
plt.show()
plt.figure()
raw_data[raw_data['Produk'] == 'B'].hist()
plt.tight_la... |
# Reprojecting a Vector Layer
# https://github.com/GeospatialPython/Learn/raw/master/MSCities_MSTM.zip
import processing
processing.runalg("qgis:reprojectlayer", "/qgis_data/ms/MSCities_MSTM.shp", "epsg:4326", "/qgis_data/ms/MSCities_MSTM_4326.shp") |
import re
import asyncio
import aiohttp
import os
import sys
import datetime
import tushare as ts
import pandas as pd
from stock.globalvar import TICK_DIR
from jobs.get_tick import init, run
def filter_open(date):
folder = TICK_DIR["stock"]
files = os.listdir(folder)
df_res = pd.DataFrame(columns=["up_spe... |
"""Top-level package for python-upwork."""
from upwork.config import Config
from upwork.client import Client
from . import routers
__author__ = """Maksym Novozhylov"""
__email__ = "[email protected]"
__version__ = "2.1.0"
__all__ = ("Config", "Client", "routers")
|
#from distutils.core import setup
from setuptools import setup, find_packages
install_requires = ['tinytools']
# import __version__
exec(open('dgsamples/_version.py').read())
setup(
name='dgsamples',
version=__version__,
author='Nathan Longbotham',
author_email='[email protected]',
pac... |
# encoding: latin2
"""clusterPy input methods
"""
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
__author__ = "Juan C. Duque, Alejandro Betancourt"
__credits__ = "Copy... |
"""Web Routes."""
from masonite.routes import Get, Post, Put, Delete, RouteGroup
ROUTES = [
Get("/", "WelcomeController@show").name("welcome"),
RouteGroup([
Get("/","LocationController@index").name("index"),
Get("/@id", "LocationController@show").name("show"),
Post("/", "LocationController@c... |
import os
import requests
import logging
import json
from django.shortcuts import redirect
from social_core.utils import handle_http_errors
from social_core.exceptions import AuthFailed
from social_core.backends.oauth import BaseOAuth2
class Auth0(BaseOAuth2):
"""Auth0 OAuth authentication backend"""
name =... |
#import pandas as pd
#import pandas_ml as pdml
import numpy as np
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
predicted = np.genfromtxt ('res/predicted1.txt', delimiter=",")
expected = np.genfromtxt ('res/expected1.txt', deli... |
from quizard_backend.models import QuizAttempt
from quizard_backend.tests import (
profile_created_from_origin,
get_fake_quiz,
get_fake_quiz_questions,
get_fake_user,
get_access_token_for_user,
)
async def test_get_own_created_and_attempted_quizzes(
app, client, users, questions, quizzes
):
... |
"""
experiments.py
Run experiments with multiple configurations.
Create a driver config specifying the experiments under configs/other.
Run as: python3 -W ignore experiments.py -b region.yaml -d driver.yaml
"""
import argparse
import copy
import datetime
import itertools
import json
import logging
import multiprocessin... |
import unittest, os
from erclient.list import communication_types_list
class TestStringMethods(unittest.TestCase):
def test_er_client_id_exists(self):
er_client_id = os.environ.get('ER_CLIENT_ID')
self.assertIsNotNone(er_client_id, "ER_CLIENT_ID Environment var is missing")
def test_er_client... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.