content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
# 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, softw... |
from iotbx import mtz
mtz_obj = mtz.object(file_name="3nd4.mtz")
# Only works with mtz.object.
# Does not work if mtz is read in with iotbx.file_reader.
miller_arrays_dict = mtz_obj.as_miller_arrays_dict()
|
import wfdb
import numpy as np
from glob import glob
import biosppy
import os
import cv2
import pandas as pd
wfdb.io.show_ann_labels()
from matplotlib import pyplot as plt
mitdb_path = '/home/jungkap/Documents/datathon/alpha.physionet.org/files/afdb/1.0.0/'
paths = glob('{}*.atr'.format(mitdb_path))
paths = [path[... |
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
basenum = 0
numcount = 0
for num in nums:
if num is not basenum:
if numcount > 0:
numcount = numcount - 1
... |
class postgresql_dataType_converter():
def __init__(self,data_I=None):
if data_I:
self.data = data_I;
else: self.data = None
def convert_torf2Boolean(self,data_I):
'''Convert t/f to boolean
INPUT:
data_I = string representation of data
OUTPUT
... |
class RenderTask:
def __init__(self, frame, max_frame):
self.frame = frame
self.max_frame = max_frame
self.started = False
self.remote_cancelled = False
self.attempts = 0
def record_failed_attempt(self):
self.attempts += 1
def failed(self):
return se... |
from tweets.models import Tweet
from tweets.models import Retweet
from tweets.models import Comment
from tweets.models import Like
from django.contrib import admin
# Register your models here.
admin.site.register(Tweet)
admin.site.register(Like)
admin.site.register(Retweet)
admin.site.register(Comment)
# admin.site.r... |
# 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... |
## Inspect, prepare and analyse data from pima indian dataset
# Adapted from Jason Brownlee's machine learning mastery in python book: https://machinelearningmastery.com/)
# https://machinelearningmastery.com/tutorial-first-neural-network-python-keras/
# (Originally from the Diabetes and Digestive and Kidney Disease, ... |
"""Unittest for vulnz dump command."""
import json
import csv
import pathlib
from click.testing import CliRunner
from ostorlab.cli import rootcli
from ostorlab.runtimes.local.models import models
def testVulnzDump_whenOptionsAreValid_jsonOutputFileIsCreated(mocker, tmpdir, db_engine_path):
"""Test ostorlab vuln... |
import numpy as np
import cv2 as cv
filename = 'images/pedestrian.jpg'
img = cv.imread(filename)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
# find Harris corners
gray = np.float32(gray)
dst = cv.cornerHarris(gray,2,3,0.04)
dst = cv.dilate(dst, None)
ret, dst = cv.threshold(dst,0.01*dst.max(),255,0)
dst = np.uint8(dst... |
import math
def generateSinLut():
lut = []
for i in range(0, 91):
lut.append(round(math.sin(math.radians(i)) * 0xFFFF))
return lut
def buildLutArray(lut):
code = "{\n "
col = 0
for i in range(0, len(lut)):
if col >= 8:
code += "\n "
col = 0
... |
import logging
import time
import psutil
import socket
import websocket
import ssl
import simplejson as json
from threading import Thread
from enum import Enum
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtCore import QDateTime, QObject, pyqtSignal, pyqtProperty, pyqtSlot
class LocalConnector(QObject):
da... |
# flake8: noqa
from rastervision2.core.data.activate_mixin import *
from rastervision2.core.data.raster_source import *
from rastervision2.core.data.crs_transformer import *
from rastervision2.core.data.label import *
from rastervision2.core.data.vector_source import *
from rastervision2.core.data.label_source import ... |
"""
Remove Molecules
================
"""
from .selector import Selector
class RemoveMolecules(Selector):
"""
Prevents a :class:`.Selector` from selecting some molecules.
Examples
--------
*Removing Molecules From Selection*
.. testcode:: removing-molecules-from-selection
import s... |
import argparse
import pandas as pd
import json
parser = argparse.ArgumentParser(description="Evaluation script")
parser.add_argument("-o", "--output", required=True)
parser.add_argument('-t', '--test', required=True)
args = parser.parse_args()
output_file = str(args.output)
test_file = str(args.test)
de... |
import logging
from pythonit_toolkit.pastaporto.entities import PastaportoUserInfo
from src.association_membership.domain.exceptions import (
CustomerNotAvailable,
NoSubscriptionAvailable,
NotSubscribedViaStripe,
)
from src.association_membership.domain.repository import AssociationMembershipRepository
l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayOpenPublicContentPublishModel(object):
def __init__(self):
self._action_url = None
self._article_id = None
self._content = None
self._cover_img = None
... |
"""Integrate with DuckDNS."""
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_DOMAIN
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.helpers.aiohttp_... |
"""Types of master fields."""
from config import Names as N
from control.typ.related import Related
class Master(Related):
"""Type class for types with values in master tables."""
widgetType = N.master
def __init__(self, context):
self.context = context
|
import datetime
import yaml
import intake_esm
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.viewcode',
'sphinx.ext.autosummary',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.extlinks',
'sphinx.ext.intersphinx',
'sphinx.ext.napoleon',
'myst_nb',
'sphinxext.ope... |
import pandas as pd
from itertools import chain
from global_constants import *
import numpy as np
def get_metaclassifier_training_data_and_labels(cv_predictions, feature_names):
'''
getting meta-classifier training data from the cv fold predictions
'''
rez_frame = None
column_feats = []
for pr... |
'''
Created on 2019年5月26日
@author: bkd
'''
from kdGUI import *
import time
from tkinter import VERTICAL
from ttkthemes import THEMES
def aa():
print("in aa")
# for theme in THEMES:
# global win
# win.setTheme(theme)
# print("theme:" + theme)
# time.sleep(5)
global theme_in... |
import pyxtermjs.app as xterm
app = xterm.app
app.config['cmd'] = '/bin/bash'
if __name__ == '__main__':
xterm.socketio.run(app, port=5000)
|
"""
CryptoAPIs
Crypto APIs 2.0 is a complex and innovative infrastructure layer that radically simplifies the development of any Blockchain and Crypto related applications. Organized around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of thei... |
#!/usr/bin/env python
# =============================================================================
# MODULE DOCSTRING
# =============================================================================
"""
General utility functions for the repo.
"""
# ================================================================... |
import dask.bag as bag
import dask_geopandas
import geopandas as gpd
import glob
import os
def load_dtype(filename):
print(f'Started {filename}')
gdf = gpd.read_file(filename, driver='SHP')
#dtype conversions
mapping = {
"AFFGEOID": "str",
"AFFGEOID20": "str",
"AIANNHCE": "int... |
import numpy as np
### Local module imports
import riptide.libcpp as libcpp
from .ffautils import generate_width_trials
from .periodogram import Periodogram
from .timing import timing
@timing
def ffa_search(tseries, period_min=1.0, period_max=30.0, fpmin=8, bins_min=240, bins_max=260,
ducy_max=0.20, wtsp=1.5, de... |
import os
DB_PATH = os.environ.get('MARKET_DB_PATH', ':memory:')
SMTP_HOST = os.environ.get('SMTP_HOST', None)
|
#!/usr/bin/env python3
import os
import re
import cv2
import keras
import numpy as np
import pandas as pd
DATA_PATH = 'cage/images/'
LEFT_PATH = 'data/left.h5'
RIGHT_PATH = 'data/right.h5'
NUM_PATH = 'data/numbers.csv'
DataSet = (np.ndarray, np.ndarray, np.ndarray)
def extract() -> (list, list):
l_data, r_data... |
from app import APP
if __name__ == '__main__':
APP.run(host='127.0.0.1', port=5000, debug=True)
|
import codecs
# please put me in a library somewhere...
# please to be porting this at the same time...
# https://github.com/exflickr/flamework/blob/master/www/include/lib_sanitize.php
# (20150831/thisisaaronland)
# I have put this in its own library! And next I will port lib_sanitize.php.
# (20160204/dphiffer)
'''
... |
import subprocess
import os
for filename in os.listdir("."):
if not filename.endswith(".csv"):
continue
if not filename.startswith("internal"):
continue
for directory in ["customer1million", "customer5million", "customer10million", "customer15million"]:
command = "python3 /home/dbco... |
from audioop import mul
from curses import flash
from flask import Blueprint, render_template, request, flash, redirect, url_for, jsonify, session
from flask_login import login_required, current_user
from configparser import ConfigParser
from numpy import number, reciprocal
from twilio.rest import Client
import os
fro... |
while True:
try:
D = input()
S = input()
if len(D.split(S)) > 1:
print('Resistente')
else:
print('Nao resistente')
except EOFError as e:
break
|
from datetime import date, timedelta
from django.test.client import Client
from django.contrib.auth.models import User
from django.db.models import Q
from django.core.urlresolvers import reverse
from django.core.cache import cache
from model_mommy import mommy
from django.test import TestCase
from django.utils.safestri... |
# from pythonwhois.net import get_whois_raw
# from pythonwhois.parse import parse_raw_whois
from core.analytics import OneShotAnalytics
from core.common.utils import tldextract_parser
from core.observables import Email, Text
def link_from_contact_info(hostname, contact, field, klass, description):
if contact is n... |
from typing import Union
from .lib.Gen import *
class Channel(object):
def __init__(self, auth):
self.auth = auth
def afterLogin(self, *args, **kwgs):
self.auth.url("/CH4")
if args:
setattr(*args)
try:
for k, v in kwgs.items():
setattr(self, k, v)
except:
pass
async def approveChannelAndI... |
from netpyne import sim
import params
# Create network and save
sim.create(netParams=params.netParams, simConfig=params.simConfig)
sim.saveData()
|
def bsearch(power, string, upper, lower):
res = 0
for i in range(power):
if string[i] == upper:
res += 2 ** ((power-1)-i)
return res
with open("input.txt", 'r') as f:
idxs = []
maxidx = 0
for l in f.readlines():
line = l.replace("\n", "")
row = bs... |
from vcub_keeper.config import FEATURES_TO_USE_CLUSTER, PROFILE_STATION_RULE, SEED
from vcub_keeper.transform.features_factory import process_data_cluster
from vcub_keeper.reader.reader_utils import filter_periode
from vcub_keeper.reader.reader import read_station_profile
from sklearn.preprocessing import StandardScal... |
#!/usr/bin/env python2
##########################################################################################
# Developers: Icaro Alzuru and Aditi Malladi
# Project: HuMaIN (http://humain.acis.ufl.edu)
# Description: Run OCRopus over all the images of an specified folder.
######################################... |
import os
import numpy as np
import pandas as pd
from base import BaseFeature
from google.cloud import storage
from itertools import combinations
class MetaFeaturesComb(BaseFeature):
def import_columns(self):
return [
"engaged_user_id"
]
def make_features(self, df_train_input, df_... |
class Solution(object):
def XXX(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ""
import operator
min_str, result = min(strs, key=len), ""
for p, i in enumerate(min_str):
if not reduce(operator... |
import random
from turtle import Turtle
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 5
class CarManager:
def __init__(self) -> None:
self.active_cars = []
self.move_distance = STARTING_MOVE_DISTANCE
self.start_positions = [in... |
"""Search and download SRTM tiles.
The module provides a `SRTM` class to search and download SRTM tiles from the
NASA EarthData server.
Examples
--------
Downloading SRTM tiles to cover the area of interest `geom` into `output_dir`::
srtm = SRTM()
srtm.authentify(username, password)
tiles = srtm.search(g... |
from json import loads
def test_session_accessor(client):
tag = 5
try:
client.session.accessor(tag=tag)
except Exception:
pass
request_data = loads(client._connection.session.post.call_args.kwargs["data"])
assert request_data["method"] == "session-get"
assert request_data["arg... |
import re
from bsddb3 import db
from datetime import datetime
# search for only id and subject
def searchid(id):
result = []
database = db.DB()
database.open("re.idx", None, db.DB_HASH,db.DB_CREATE)
curs = database.cursor()
iter = curs.first()
# traverse the database from first to last
while... |
from synonym import get_synonym
from definition import get_definition
from ignore import should_ignore
def methodical_compute_word(idx, word):
#dont want anything different for first word
if not idx or should_ignore(word): return word
if not idx % 3:
return get_synonym(word)
elif not idx... |
# coding: utf-8
from pandas import DataFrame, Series, to_datetime
from zeep import Client
from zeep.helpers import serialize_object
from concurrent.futures import ThreadPoolExecutor
from functools import wraps
from time import time
from hielen.utils import isot2ut
"""
sudo apt-get install libxml2-dev libxslt1-dev
pi... |
from django.db.models.manager import Manager
try:
from django.db import router
except:
pass
class SharedMemoryManager(Manager):
# CL: this ensures our manager is used when accessing instances via
# ForeignKey etc. (see docs)
use_for_related_fields = True
# CL: in the dev version of django, Re... |
import os
from echo.qt import autoconnect_callbacks_to_qt, connect_checkable_button
from glue.utils.qt import load_ui
from qtpy.QtWidgets import QCheckBox, QVBoxLayout, QWidget
class NetworkLayerStateWidget(QWidget):
def __init__(self, layer_artist):
super().__init__()
# self.checkbox = QCheckB... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Dict, Optional, Type
from ax.core.metric import Metric
from ax.metrics.branin import BraninMetric
f... |
import math
import pandas as pd
import numpy as np
def generate_feature_matrix(raw_data, features):
X_df = pd.DataFrame()
if 'Longitude' in features:
X_df['Longitude'] = raw_data['Longitude']
if 'Latitude' in features:
X_df['Latitude'] = raw_data['Latitude']
if 'Speed'... |
import os
from yolox.data.datasets.voc_classes import VOC_CLASSES
import matplotlib.pyplot as plt
import classmap
import numpy as np
from sklearn.metrics import confusion_matrix
def get_confusion(gt, pr, clas, gt_counter):
gt_values = np.array(list(gt_counter.values()))
guess = gt
fact = pr
... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 cop... |
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
import json
import scipy.ndimage.morphology as scimorph
import os
import matplotlib.pyplot as plt
from matplotlib import colors
class MapSDF():
def __init__(self, params):
# params
self.res = params['res... |
import sys
sys.path.insert(0, "src")
import tensorflow as tf
import argparse
import os
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--out_dir", default="out", type=str, help="Out dir")
parser.add_argument("--pretrained_model", type=str, required=True)
args = parse... |
from __future__ import print_function
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision import transforms
def conv_block(in_channels, out_channels, pool=False):
layers = [nn.Con... |
#!/usr/bin/python
import unirest
import simplejson as json
class messages:
def __init__( self, id='0',roomId='0',text='0',personId='0'):
self.id = id
self.roomId = roomId
self.text = text
self.personId = personId
class rooms:
def __init__( self, id='0'):
self.id ... |
import pandas as pd
import numpy as np
i = pd.Index(["AbC", "de", "FGHI", "j", "kLm"])
other = (
np.array(["f", "g", "h", "i", "j"]),
np.array(["f", "a", "b", "f", "a"]),
np.array(["f", "g", "h", "i", "j"]),
np.array(["f", "a", "b", "f", "a"]),
np.array(["f", ... |
from testUtils.AbstractTest import AbstractTest
from time import sleep
from psutil import Process, NoSuchProcess
from typing import List, Optional
from re import search
from os.path import join
from testUtils.Utils import PWrap, printTester, studSaveStrComp
class TestInput(AbstractTest):
# Our process wrapper inst... |
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
def plot_individual(df: pd.DataFrame, cmip_model: str, spatial_res: int) -> None:
plt.style.use(["seaborn-poster"])
# subset data
df = df[df["cmip"] == cmip_model]
df = df[df["spatial"] == spatial_res]
fig, ax = plt.subpl... |
import numpy as np
import torch
class Dataset(torch.utils.data.Dataset):
def __init__(self, data, device="cpu"):
mesh = np.stack(np.meshgrid(*data), -1).reshape(-1, len(data))
self.X = torch.from_numpy(mesh).float().to(device)
def __len__(self):
return len(self.X)
def... |
#
# This configuration is intended to be used to study errors spotted in the L1TEMU DQM output
#
# It can be run over streamer files or root files and outputs only events that fail the comparison.
#
# Alex Tapper 8/9/10
#
process = cms.Process('GctErrorFilter')
process.load("FWCore.MessageLogger.MessageLogger_cfi")
p... |
from django import forms
class OfficialInfoForm(forms.Form):
official_register_number = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'LM10'}))
official_register_date = forms.CharField(widget=forms.DateInput(attrs={'placeholder': '22-07-1990'}))
class PersonalInfo(forms.Form):
full_name = ... |
import numbers
import torch
from torch import nn
from math import pi
def ColourDistortion(s=1.0):
color_jitter = TensorColorJitter(0.8*s, 0.8*s, 0.8*s, 0.2*s)
rnd_color_jitter = TensorRandomApply([color_jitter], p=0.8)
rnd_gray = TensorRandomApply([TensorGrayscale()], p=0.2)
color_distort = ModuleComp... |
#Задача 3. Вариант 22
#Напишите программу, которая выводит имя "Филип Ауреол Теофраст Бомбаст фон Гогенгейм", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире.
#Rudich A.C.
#08.03.2016
print("Сегодня речь пойдёт про Филипа Аурео... |
#!/usr/bin/env python
#
# Copyright 2018 Flavio Garcia
#
# 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 ... |
import numpy as np
import cv2
import mlearn
from keras.utils import to_categorical
import os
from pretreatment import load_data, phash
def load_true_labels(path='classify-true'):
filelist = os.listdir(path)
class_result = [(int(f.split('.')[0]), int(f.split('.')[1])) for f in filelist]
class_re... |
import re
from typing import List, Union
class ForwardedHeader:
_FOR_REGEX = re.compile(r"for=\"?([\[\]:.a-z0-9]+)\"?", flags=re.IGNORECASE)
_BY_REGEX = re.compile(r".*by=\"?([\[\]:.a-z0-9]+)\"?.*", flags=re.IGNORECASE)
_PROTO_REGEX = re.compile(r".*proto=([a-z]+).*", flags=re.IGNORECASE)
_HOST_REGEX ... |
from distutils.core import setup
setup(
name='pycra',
packages=['pycra'],
version='1.0.2',
description='Python Challenge Response Authentication with PBKDF2 Hashed Passwords',
author='Alexander Kleinschmidt (kungalex)',
author_email='kung4lex@gmail.com',
license='MIT',
... |
from netmiko import ConnectHandler
def takebackup(cmd,rname):
uname="cisco"
passwd="cisco"
device = ConnectHandler(device_type='cisco_ios', ip=rname, username=uname, password=passwd)
output=device.send_command(cmd)
fname=rname+".txt"
file=open(fname,"w")
file.write(output)
file.close()
... |
import asyncio
import math
import os
import random
import time
import typing
import discord
from discord.ext import commands
from rockutils import customchecks, rockutils
class GuildManagement(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.group(
name="guild",
des... |
from .kernel import Kernel
def kernel(*args, **kwargs):
# @okl.kernel
if (len(args) == 1 and
len(kwargs) == 0 and
callable(args[0])):
return Kernel(args[0])
# okl.kernel(*args, **kwargs)
def _kernel(func):
return Kernel(func, **kwargs)
return _kernel
|
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
def Compute_Block(cell_gradient_box):
k=0
hog_vector = np.zeros((bin_size*4*(cell_gradient_box.shape[0] - 1)*(cell_gradient_box.shape[1] - 1)))
for i in range(cell_gradient_box.shape[0] - 1):
for j in range(cell_gradient... |
import os
import io
from . import _common
from ._common import as_file, files
from .abc import ResourceReader
from contextlib import suppress
from importlib.abc import ResourceLoader
from importlib.machinery import ModuleSpec
from io import BytesIO, TextIOWrapper
from pathlib import Path
from types import ModuleType
f... |
from pydantic.main import BaseModel
from pydantic.networks import EmailStr
from chat_room.core.response import BaseResponse
class LoginResponse(BaseModel):
auth_token: str
refresh_token: str
class AuthLoginSchema(BaseModel):
email: EmailStr
password: str
class RefreshTokenSchema(BaseModel):
re... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 15 19:00:05 2020
@author: Andres Angeles Albores
View functions go here
"""
from flask import render_template, flash, redirect, url_for
from app import app
from app.forms import LoginForm
@app.route('/')
@app.route('/index')
def index():
user = {'username': 'Andres... |
import unittest
from mock import patch
from ibmcloud_python_sdk.vpc.instance import Instance
from tests.Instance import Instance as instance
from tests.Common import Common
class InstanceTestCase(unittest.TestCase):
"""Test case for the client methods."""
def setUp(self):
self.patcher = patch('ibmcl... |
# -*- coding: utf-8 -*-
import pyowm
#KEY = "c613d7fb9e2ec98823f8bbb8de7befc4" # default
KEY = "de79ebae33363e14394e058db03512aa" # nanny
class Weather:
def __init__(self, location="Quebec,ca"):
self.owm = pyowm.OWM(KEY)
self.location = location
self.get_obs()
def get_obs(self):
... |
# Following http://web.engr.illinois.edu/~bkclark/PIMCTutorial/tutorial.pdf
import CalcStatistics
import numpy
import os
import pylab
import random
from PIMCHelp import *
class PathClass:
def __init__(self,beads,tau,lam):
self.tau=tau
self.lam=lam
self.beads=beads.copy()
self.NumTimeSlices=len(b... |
# -*- coding: utf-8 -*-
import logging
from typing import Union
from aiodocker.containers import DockerContainers
from aiodocker.exceptions import DockerError
from aiodocker.networks import DockerNetworks
from playground.control.attribs import ContainerDeleteAttribs
from playground.control.command import PlaygroundC... |
'''
Implementation of various machine learning representations for molecules
'''
import setuptools
from distutils.core import setup
def setup_chemreps():
setup(
name='chemreps',
maintainer='Dakota Folmsbee, Amanda Dumi, Shiv Upadhyay',
maintainer_email='dfolmsbee@gmail.com, amandaedumi@gma... |
import sys
print sys.excutable
|
from __future__ import absolute_import, division, print_function
import cctbx.array_family.flex as flex# import dependency
import sys
import boost.python
ext = boost.python.import_ext("iotbx_ccp4_map_ext")
from iotbx_ccp4_map_ext import *
import iotbx_ccp4_map_ext as ext
class utils : # These routines are used by bo... |
import pytest
import sciwing.constants as constants
import pathlib
from sciwing.datasets.seq_labeling.seq_labelling_dataset import (
SeqLabellingDatasetManager,
)
from sciwing.utils.common import chunks
from sciwing.modules.embedders.trainable_word_embedder import TrainableWordEmbedder
import torch
from sciwing.uti... |
from __future__ import division, print_function
import numpy as np
import random
class MultiArmBandit(object):
"""docstring for MultiArmBandit."""
def __init__(self, arms, est = None, mode=1, epsilon=0.1):
"""
mode = 1 epsilon greedy
mode = 2 epsilon decreasing
"""
super(MultiArmBandit, self).__init__()
... |
from django.urls import path
from . import views
app_name = "login"
urlpatterns = [
path('', views.signin, name='signin'),
path('index/', views.index, name='index'),
path('signup/', views.signup, name="signup"),
path('signin/', views.signin, name="signin"),
path('signout/', views.signout, name="s... |
from spaceone.api.inventory.v1 import region_pb2, region_pb2_grpc
from spaceone.core.pygrpc import BaseAPI
class Region(BaseAPI, region_pb2_grpc.RegionServicer):
pb2 = region_pb2
pb2_grpc = region_pb2_grpc
def create(self, request, context):
params, metadata = self.parse_request(request, context... |
"""Test Survey collect_stats and dead_traces-related methods"""
# pylint: disable=redefined-outer-name
import pytest
import numpy as np
from seismicpro import Survey, make_prestack_segy
from seismicpro.src.const import HDR_DEAD_TRACE
from . import assert_surveys_equal, assert_survey_processed_inplace
def gen_rando... |
rabbit = dict()
input = 444
rabbit["adult"] = input
rabbit["teen"] = 0
rabbit["baby"] = 0
for i in range(0,365,15):
if i % 30 == 0 and i != 0:
rabbit["baby"] = int(rabbit["baby"] * 0.75)
rabbit["teen"] = int(rabbit["teen"] * 0.75)
rabbit["adult"] = int(rabbit["adult"] * 0.75)
temp_te... |
from datetime import datetime
from private import bankcodes_api_key as api_key
from . import data_path, dateformat_log
api_path = data_path + 'bank_codes/'
counter_path = "%scounter.%s.txt" % (api_path, datetime.now().strftime(dateformat_log[:6]))
limit = 19
key = api_key
counter = False
|
# OpenWeatherMap API Key
weather_api_key = "5046ef379a87de7f0cf0a2897acbf4f1"
# Google API Key
g_key = "AIzaSyCeUhVBiXJAJ_l6pCdsdBmUdbri9FyhWbw"
|
from rest_framework import serializers
from .models import *
from store.serializers import ProductsSerializer
class OrderItemSerializer(serializers.ModelSerializer):
class Meta:
model = OrderItem
fields = (
"price",
"product",
"quantity"
)
class OrderSe... |
#!/usr/bin/env python3.8
"""
prime numbers below N
"""
def primes(N):
"""
create a list of N numbers
starting from p = 2 to p <= sqrt(N)
mark multiples of p from p*p to N+1
"""
primes = [True] * (N+1)
primes[0], primes[1] = False, False
p = 2
while p * p <= N: # we stop when p*p > N as no number above p w... |
# Generated by Django 2.1.15 on 2020-06-24 00:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('qa', '0054_testlistinstance_include_for_scheduling'),
]
operations = [
migrations.AddField(
model_name='test',
name... |
# importing the required libraries
import os
class Dataset:
name = 'Fer2013'
train_folder = 'features/Training'
validation_folder = 'features/PublicTest'
test_folder = 'features/PrivateTest'
trunc_trainset_to = -1
trunc_validationset_to = -1
trunc_testset_to = -1
class Hyperparams:
r... |
import typing
def fb_dict_factory(var_list: typing.List[typing.Tuple]):
return {var[0]: var[1] for var in var_list if var[1] is not None}
|
/usr/local/lib/python3.5/fnmatch.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.