text stringlengths 38 1.54M |
|---|
import pytest
from msdsl.lfsr import LFSR
@pytest.mark.parametrize('n', list(range(3, 19)))
def test_lsfr(n):
lfsr = LFSR(n)
state = 0
passes = []
for i in range(2):
passes.append([])
for _ in range((1<<n)-1):
passes[-1].append(state)
state = lfsr.next_state(sta... |
from gym.envs.registration import register
register(
id='bataille_corse-v0',
entry_point='gym_bataille_corse.envs:BatailleCorseEnv',
kwargs={'playersNumber': 2}
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .API import SurfsharkAPI, AuthorizationRequired
class UserSession():
FAIL = 0
SUCCESS = 1
NEED_2FA = 2
def __init__(self, tokens=None):
self.api = SurfsharkAPI(tokens=tokens)
self.tokens = None
self.logged_in = False
def ... |
"""
read a text file with a single URL on each line and
save the contents of each to a file
"""
import sys
import urllib2
urlfilename = 'urls.txt'
if len(sys.argv) > 1:
urlfilename = sys.argv[1]
urlfile = open(urlfilename, 'r')
for (i, url) in enumerate(urlfile):
wd = urllib2.urlopen(url)
fd = open('f... |
"""
USM 作业code
"""
import numpy as np
import math
from scipy import linalg
from sympy import *
from scipy.stats import norm
import matplotlib.pyplot as plt
"""
matrix1 = np.array([[100, 32, -48, 0, 0],
[32, 64, 51.2, 0, 0],
[-48, 51.2, 256, 0, 0],
[0, 0, 0, 2... |
# -*- coding: utf-8 -*-
from tools.system import FileManager
from Singleton import Singleton
class Dialog(metaclass = Singleton):
''' Printing messages in current language
The class is a singleton.
serviceExpressions: the data from the data base file.
'''
serviceExpressions: l... |
import cv2
import os
import numpy as np
from numpy import array
import pickle
from pathlib import Path
from collections import Counter
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
d = 8
k = 3
confusion_dir = 'confusion/'
confusion_mat_dir = 'confusion_matrice/'
... |
from rest_framework import serializers
from babycare.models import Like
class LikeSerializer(serializers.ModelSerializer):
like_id = serializers.IntegerField(read_only=True, source='id')
event_id = serializers.IntegerField(read_only=True, source='event.id')
like_user_id = serializers.IntegerField(read_on... |
"""
Some simple time operations that I frequently use
"""
import argparse
import arrow
def main():
"""Main function"""
args = _get_args()
args.func(args)
# End def
def _get_args():
parser = argparse.ArgumentParser(description='Some simple time operations')
subparsers = parser.add_subparsers()
... |
n = 20
mat = [[] for i in range(n)]
for i in range(n):
line = input()
mat[i] = list(map(int, line.split()))
dx = [0, 1, 0, -1, 1, 1, -1, -1]
dy = [1, 0, -1, 0, 1, -1, 1, -1]
def valid(n, i, j):
return i >= 0 and i < n and j >= 0 and j < n
ans = 0
for i in range(n):
for j in range(n):
for d in range(8):
if va... |
from pygridtools.viz import _viz_bokeh
import pytest
from pygridgen.tests import raises
def test__plot_domain(simple_boundary):
with raises(NotImplementedError):
fig1 = _viz_bokeh._plot_domain(x='x', y='y', data=simple_boundary)
fig2 = _viz_bokeh._plot_domain(x=simple_boundary['x'], y=simple_boun... |
"""Unit Testing for Fiddlewith"""
from unittest import TestCase
from fiddlewith.calc import Calculator
class TestCalculator(TestCase):
"Unit Testing class for FiddleWith"
def test_add(self):
"test for add"
calc = Calculator()
self.assertTrue(calc.add(3, 2) == 5)
|
# -*- coding: utf-8 -*-
"""
剑指 Offer 59 - I. 滑动窗口的最大值
给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。
示例:
输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7... |
#!/usr/bin/env python
# Copyright 2012 Google Inc. 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 ... |
'''
Created on 13.03.2017
@author: alex
'''
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
import scipy.misc
#close existed
for i in plt.get_fignums():
print 'has existed'
plt.close(plt.figure(i))
img = scipy.misc.imread("../../data/images/phone.png")... |
from flask_restful import Resource
from flask import request
import secrets, postgresql, os
from config import DATABASE_PATH, UPLOAD, LINK
database = postgresql.open(DATABASE_PATH)
class EducationVerefizied(Resource):
def update(self, id):
token = request.headers.get('token', False)
... |
#Solve this equation for x with python:
#x**2 = 4**3+17
sum= 4**3 +17
print (f'{sum}')
x = sum ** (1/2)
print (f'{x}') |
import os
PROJECT_ROOT_ENV = 'GAUGE_PROJECT_ROOT'
STEP_IMPL_DIR_ENV = 'STEP_IMPL_DIR'
STEP_IMPL_DIR_NAME = os.getenv(STEP_IMPL_DIR_ENV) or 'step_impl'
def get_project_root():
try:
return os.path.abspath(os.environ[PROJECT_ROOT_ENV])
except KeyError:
return ""
def get_step_impl_dir():
re... |
# -*- coding:utf-8 -*-
# -------------------------------
# ProjectName : autoDemo
# Author : zhangjk
# CreateTime : 2020/12/5 16:51
# FileName : day7.3
# Description :eggs
# --------------------------------
try:
__import__('pkg_resources').declare_namesapce(__name__)
except ImportError:
from pkgutil import exte... |
import sqlite3
def Process(dbname):
try:
conn = sqlite3.connect(dbname) # DB생성
cur = conn.cursor()
sql = "drop table if exists emp"
cur.execute(sql)
sql = "create table if not exists emp(id integer primary key, name text)"
cur.execute(sql)
# 데이터 입력
... |
# Generated by Django 2.0.13 on 2019-06-13 00:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pinball', '0002_auto_20190612_1946'),
]
operations = [
migrations.AlterField(
model_name='pinball',
name='coils',
... |
from libs.mixins import *
__all__ = [
'Psychic',
]
class Psychic(StoreMixin):
def __init__(self, data):
super().__init__()
if data:
self.data = data
else:
self.data = [
{'id': 0, 'name': 'Vlad', 'assumptions': [], 'index_effectivity': 0},
... |
# """
# To see an example of the Wikipedia API JSON look at this url:
# https://en.wikipedia.org/api/rest_v1/page/summary/Japanese_cuisine
# """
import requests
def my_function(title, value):
url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{title}"
req = requests.get(url)
data = req.json()
if... |
import numpy as np
import cv2
#You can add your own Template.png and this code will use
#your webcam and look after this template with a threshold
#my template
template_color = cv2.imread('Template.png')
#dont need this but good for troubleshooting of the wrong template
cv2.imshow('template', template_color)
#caputr... |
from flask import Blueprint
from flask_restful import Api
from app_blueprint.tree.main import Main
trees = Blueprint('trees', __name__)
api = Api(trees)
api.add_resource(Main, "/")
|
from app import db
from datetime import datetime
class Record(db.Model):
__tablename__ = 'records'
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
co2 = db.Column(db.Integer)
hum = db.Column(db.Float)
temp = db.Column(... |
#!/bin/python
# Author: Daniel Beyer
# CS372 - Project 1: Chat server/client
# 10/24/17
import sys
from socket import *
serverHandle = "MrServer" #server name
#Function where chat loop happens
def chatLoop(conn):
while 1: #Loop runs continuously
rec_data = conn.re... |
from django.db import models
class Country(models.Model):
"""
Model that represents a country.
"""
name = models.CharField(null=False, blank=False, max_length=250)
code = models.CharField(null=False, blank=False, max_length=10, unique=True)
def __str__(self):
return '{} - {}'.format(s... |
from .type import Type
from .complex import Complex, Real, Im
from .matrix import Matrix, Vector
from .function import Function, ListFunction
from .polynomial import *
|
# app/urls.py
from django.conf.urls import url
from app import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^test/$', views.test, name='test'),
url(r'^profile/$', views.profile, name='profile'),
url(r'^model/$', views.model, name='model'),
url(r'^predict/$', views.predict, name='predict'),... |
print("="*30,"[Conversao de BASES]","="*30)
escolha = 0
while escolha != 4:
value = int(input("Digite um valor para a conversao: "))
print("\nEscolha uma das opcoes:\n")
print("[ 1 ] Conversao do numero em HEXADECIMAL.")
print("[ 2 ] Conversao do numero em OCTAL.")
print("[ 3 ] Conversao do numero... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-30 01:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainsite', '0003_auto_20170729_2156'),
]
operations = [
migrations.CreateMo... |
# Generated by Django 2.1.15 on 2021-02-08 03:52
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('t', '0004_auto_20210208_1151'),
]
operations = [
migrations.RenameField(
model_name='department',
old_name='patient_id',
... |
"""
Created by Jonas Pfeiffer on 26/04/17.
"""
import csv
import os
import pickle
import numpy as np
import scipy.io
from matplotlib import pyplot
from peakutils.plot import plot as pplot
def read_lable_dict():
with open('training2017/REFERENCE.csv', mode='r') as infile:
reader = csv.reader(infile)
... |
## Generators
def make_generators_generator(g):
"""Generates all the "sub"-generators of the generator returned by
the generator function g.
>>> def ints_to(n):
... for i in range(1, n + 1):
... yield i
...
>>> def ints_to_5():
... for item in ints_to(5):
... ... |
import pytest
import json_provider
import rest_client
from data import Valid_User, Invalid_User
# @pytest.fixture()
# #user (with email & password)
@pytest.fixture(scope="session")
def valid_user():
return Valid_User
@pytest.fixture(scope="session")
def json():
return json_provider
@pytest.fixture(scope="... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup #required to parse html
import requests #required to make request
#read file
with open(r'C:\Users\Shravya.Shanmukh\Desktop\URL.csv','r') as f:
csv_raw_cont=f.read()
#split by line
split_csv=csv_raw_cont.split('\n')
#remove empt... |
import json
class Config:
def __init__(self):
self.telegram = {}
self.discord = {}
def loads(self, config_file=None):
configures = {}
if config_file:
try:
with open(config_file) as f:
data = f.read()
configu... |
import etherscan.accounts as accounts
from etherscan.blocks import Blocks
from etherscan.contracts import Contract
from etherscan.proxies import Proxies
import etherscan.stats as stats
import etherscan.tokens as tokens
import etherscan.transactions as transactions
import json
from pandas.io.json import json_normalize
i... |
a = int(input())
b = a
result = a ** 2
while b != 0:
a = int(input())
b += a
result += a ** 2
if b == 0:
break
print(result)
|
import cv2
# img = cv2.imread('./frame_imgs/62清晰度异常/0.jpg', cv2.IMREAD_GRAYSCALE)
# img = cv2.imread('./frame_imgs/62清晰度异常/10.jpg', cv2.IMREAD_GRAYSCALE)
img = cv2.imread('./frame_imgs/116亮度异常/0.jpg', cv2.IMREAD_GRAYSCALE)
# img = cv2.imread('./frame_imgs/116亮度异常/10.jpg', cv2.IMREAD_GRAYSCALE)
x = cv2.Sobel(img, cv2.... |
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait # 显式等待
from lxml import etree
import os
import requests
import re
import time
class Wz_spider():
driver_path = r'E:\ChromeDriver\chromedriver.exe'
def __init__(self):
# self.option = webdriver.ChromeOptions()
... |
from select import select
from errno import ECONNREFUSED, ENOENT, EAGAIN
from time import sleep
from math import isnan
from io import BytesIO
import logging
import msgpack
import socket
import pyev
from fluxmonitor.player.main_controller import MainController
from fluxmonitor.err_codes import (
SUBSYSTEM_ERROR, ... |
from setuptools import setup, find_packages
import re
import ast
# version parsing from __init__ pulled from Flask's setup.py
# https://github.com/mitsuhiko/flask/blob/master/setup.py
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open('q2_plotly/__init__.py', 'rb') as f:
hit = _version_re.search(f.read... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 25 11:44:42 2020
@author: Admin
"""
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score,confusion_matrix
Train_Data= pd.read_csv('CrashTest_TrainData.csv')
Test_Data=p... |
from urllib.parse import parse_qs
from oic.utils.authn.user import UsernamePasswordMako
from oic.utils.authn.user import logger
from oic.utils.http_util import SeeOther
from oic.utils.http_util import Unauthorized
__author__ = "danielevertsson"
class JavascriptFormMako(UsernamePasswordMako):
"""
Do user aut... |
from onmt.translate.Translator import Translator
from onmt.translate.TranslatorMultimodal import TranslatorMultimodal
from onmt.translate.Translation import Translation, TranslationBuilder
from onmt.translate.Beam import Beam, GNMTGlobalScorer
__all__ = [Translator, TranslatorMultimodal, Translation,
Beam, ... |
import sys
import os
import glob
import time
import unittest
import gevent.testing as greentest
from gevent.testing import util
this_dir = os.path.dirname(__file__)
def _find_files_to_ignore():
old_dir = os.getcwd()
try:
os.chdir(this_dir)
result = [
'wsgiserver.py',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Lia Thomson
cyanoConstruct file to run (because there is currently no __main__ file)
"""
import os
from sys import path as sysPath
sysPath.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from cyanoConstruct import app
if(__name__ == "_... |
#!/usr/bin/env python
import sys
import os
if __name__ == '__main__':
if len(sys.argv) != 2:
print 'Usage: ./generate_img_abspath_list.py <image_dir_root>\n'
print 'Output: <image_dir_root>/result.txt'
exit(1)
root = os.path.abspath(sys.argv[1])
result_path = root + '/result.t... |
from django.shortcuts import render
from budgetApp.models import Stuff
from budgetApp.forms import NewCategory
# Create your views here.
def index(request):
form = NewCategory()
budget_list = Stuff.objects.order_by('top_name')
amount_budgeted = 0
amount_spent = 0
income = 0
for i in budget_li... |
import random
list_of_choices = ["Rock", "Paper", "Scissors"]
your_wins = 0
comp_wins = 0
num_of_rounds = int(input("What do you want to play to? Best of: 5, 7, 9, etc."))
while((your_wins or comp_wins) < num_of_rounds*.5):
player_choice = input("Rock, Paper, or Scissors?")
comp_choice = random.choice... |
from numpy import linspace,pi,sin,cos
from multiprocessing import cpu_count
class Config:
def __init__(self):
self.resolution=(1000,1000)
#only enable if you have imageMagick installed
self.saveAnimaiton=True
tRange=(0,2*pi)
totalFrames=160
self.framerate=30
... |
from django.db import models
from unifier.apps.core.models.base import StandardModelMixin
from unifier.apps.core.models.manga import Manga
from unifier.apps.core.models.novel import Novel
class Platform(StandardModelMixin):
class Meta:
verbose_name = "Platform"
verbose_name_plural = "Platforms"
... |
# -*- coding: utf-8 -*-
#!/usr/bin/python
'''
-İki algoritmanin karmaşıklığıda O(n) dir.
-Lomuto Partition listeyi 4 kısma böler. Bunlar pivot,pivottan küçük ve pivottan büyük ve belirsiz kısım
şeklindedir
-Hoare Partion da ise liste pivottan küçük ve büyük olmak üzere 2 kısıma ayrılır.
- Swaping işlemleri Hoare Part.... |
if __name__=="__main__":
T = int(raw_input())
for _ in range(T):
N = int(raw_input())
arr = [ [0 for i in range(N+1)] for i in range(3) ]
arr[0] = map(int, raw_input().split())
##
for i in range(N):
... |
##
from bs4 import BeautifulSoup
import pandas as pd,requests,io
import acqua.aqueduct as aq
gestore = "TeaAcqueMantova"
aq.setEnv('Lombardia//'+gestore)
url = 'https://www.cometea.it/verifica-la-tua-acqua/'
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
#
map = soup.findAll("area", {"shape": "... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from kuon.common import CommonSteamGames
from kuon.steam.common import SteamUrls
from kuon.steam.steam import Steam
class IInventory(Steam):
"""Implementation of the API methods related to the inventory of the user on Steam
common not self explanatory keys:
a... |
class ServerBaseException(Exception):
"""Base class for server errors for server."""
def __init__(self, *args):
try:
if args and isinstance(args[0], str):
self.value = args[0]
except Exception:
raise Exception
class ServerMethodException(ServerBaseExc... |
from braces.views import PrefetchRelatedMixin
from django.contrib.auth import login, logout
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import redirect_to_login
from django.forms import HiddenInput
from django.http imp... |
from django.urls import path
# from . import views
from .views import *
from django.contrib.auth.views import LoginView, LogoutView
urlpatterns = [
# path('', indexView.as_view(), name='home'),
path('', indexView, name='home'),
path('test/', test_View, name='test'),
path('m-test/', mohit_test_view, nam... |
#!/usr/bin/python
import sys
fname1 = sys.argv[1]
fname2 = sys.argv[2]
if len(sys.argv) > 3:
new_col_name = sys.argv[3]
else:
new_col_name = None
id_set = set()
with open(fname2) as f:
id_set = set(l.rstrip() for l in f)
if fname1 != "stdin":
if fname1.endswith(".gz"):
i_file ... |
import sqlite3
conn = sqlite3.connect('eventos.db')
cursor = conn.cursor()
id = 3
# excluindo um registro da tabela
cursor.execute("""
DELETE FROM clientes
WHERE id = ?
""", (id))
conn.commit()
print('Registro excluido com sucesso.')
conn.close() |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import KMeans
def InitCenter(k,m,x_train):
#取数据集中前k个点作为初始中心
Center = np.zeros([k,n]) #从样本中随机取k个点做初始聚类中心
np.random.seed(15) #设置随机数种子
for i in range(k):
... |
import json
import os
from string import Template
from flask import request, jsonify
from helpers import query, update, log, generate_uuid
from escape_helpers import sparql_escape_uri, sparql_escape_string, sparql_escape_int, sparql_escape_datetime
import pandas as pd
from .file_handler import postfile
def store_j... |
#coding=UTF-8
import threading
class jd_Threadings(threading.Thread):
def __init__(self,keyword,id,obj):
#threading.Thread.__init__(self)
super(jd_Threadings,self).__init__()
self.keyword=keyword
self.id=id
self.obj=obj
self.lock=threading.Lock()
def run(self):
self.lock.acquire()
pr... |
import sys
'''
先对一跳的句子进行搜索,选取最大的n个,然后再找n个实体相连的候选路径进行计算,选择得分最高的
'''
sys.path.insert(0,'/home/aistudio/work/MyExperiment/path_ent_rel')
sys.path.insert(0,'/home/hbxiong/QA2/path_ent_rel')
from keras_bert import load_trained_model_from_checkpoint
import keras
import json
from py2neo import Graph
from some_function_maxb... |
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from plone.app.layout.viewlets.common import ViewletBase
class CSS(ViewletBase):
def available(self):
return True
|
## The Data Analysis Process- Drawing Conclusions Quiz ##
"""
This quiz was done on my own with research.
"""
# imports and load data
import pandas as pd
% matplotlib inline
df = pd.read_csv('store_data.csv')
df.head()
"""
This function selects specific rows in specific columns so that you can apply
statistical func... |
import sys
sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
from keras.models import load_model
import cv2
import numpy as np
noise = []
noise = np.random.normal(0, 1, [100, 100])
noise = np.array(noise)
print(noise.shape)
model = load_model('facegeneratorep100.hdf5')
pr = model.predict(noise)
pr = ((pr... |
__author__ = 'karthikb'
a = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14]
a1 = [20, 25, 1, 3, 4, 5, 7, 10, 14, 15, 16, 19]
a2 = [1,2,3,4]
def special_binary(a,left,right):
mid = (right + left) //2
print a[low:right]
if a[left] < a[right]:
return a[left]
elif a[mid - 1] >= a[mid] and a... |
import os
from datetime import timedelta
class Config(object):
SECRET_KEY = 'kaadfadfafafdafafadddddadfadadfaffddddddd'
# REMEMBER_COOKIE_DURATION = timedelta(seconds=20)
# SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://armandosuazo:a1234567@armandosuazo.mysql.pythonanywhere-services.com/medi... |
import os
import math
import numpy
import nltk
import re
class LexRank(object):
def __init__(self):
self.text = Preprocessing()
self.sim = DocumentSim()
def score(self, sentences, idfs, CM, t):
Degree = [0 for i in sentences]
n = len(sentences)
for i in range(n):
for j in range(n):
CM[i][j] = se... |
#basic lib to work with dataset
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
#libraries to work with the anonymity of the proc(Data)
from cn.protect import Protect
from cn.protect.privacy import KAnonymity
from cn.protect.hierarchy import DataHierarchy, Orde... |
import math
import networkx as nx
import pandas as pd
import numpy as np
import random
from time import process_time
k = int(input("Enter a k: "))
maxServer = int(math.pow(k, 3) / 4)
print('CHECK: Max amount of servers given k = ', k, ' is ', maxServer, 'servers')
# initializing
coreCT = int(math.pow((k /... |
import sublime
import sublime_plugin
import base64
class EncodeCommand(sublime_plugin.TextCommand):
def run(self, edit):
selection = self.view.sel()
for region in selection:
region_text = self.view.substr(region)
randomized_text = base64.b64encode(bytes(region_text.strip(), ... |
import unittest
from data_action import get_data
from data_action import delete_data
test_url_1 = "https://data.seattle.gov/resource/4xy5-26gy.csv"
test_url_2 = "https://data.seattle.gov/resource/4xy5-27gy.csv"
class TestDataAction(unittest.TestCase):
# Test get_data function
def testGetData(self):
... |
import unittest
from unittest.mock import Mock
from src.combat.combat import Combat
from src.elemental.ability.ability import Target
from src.elemental.combat_elemental import CombatElemental
from src.team.combat_team import CombatTeam
from src.team.team import Team
from tests.character.character_builder import NPCBui... |
if __name__ == '__main__':
# Read feature files
bert_feature_index_start = open('output/test_set_bert_features.txt', 'r')
main_features = open('output/features.txt', 'r')
word_feature_index_start = open('output/word_distance_features.txt', 'r')
# Create ultimate feature file
feature_file = op... |
"""
For cases in which an entire view function needs to be made available
only to users with certain permissions, a custom decorator can be used.
Example usage:
@main.route('/admin')
@login_required
@admin_required
def for_admins_only():
return "For administrators!"
@main.route('/moderator')
@login_required
@permi... |
"""
This contains implementations of:
synflow, grad_norm, fisher, and grasp, and variants of jacov and snip
based on https://github.com/mohsaied/zero-cost-nas
"""
import torch
import logging
import math
from naslib.predictors.predictor import Predictor
from naslib.predictors.utils.pruners import predictive
logger = l... |
#!/usr/bin/env python
"""
A quick utility script to mark analyzed songs as analyzed.
A song has been analyzed if any notes contain a non-NULL root.
$ python -m utils.mark_analyzed [-t DBPOOL_SIZE] [-u USERNAME] [-p PASSWORD]
where:
- DBPOOL_SIZE is the number of databases
- USERNAME is the database userna... |
# -*- coding: utf-8 -*-
from django import forms
from cadastro.models import Inscricao
class InscricaoForm(forms.ModelForm):
nome = forms.CharField(max_length=300)
tipo_pessoa = forms.CharField(max_length=100)
cpf_cnpj = forms.CharField('cpf_cnpj', max_length=20, unique=True)
rg = forms.C... |
#encoding=utf8
from models import *
#from serializers import *
from django.db.models import Q
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework import renderers
from rest_framework.dec... |
# coding=utf-8
from pytest_bdd import (
scenario
)
@scenario('../features/redshift_node_metrics_percentage_disk_space_used.feature',
'Create redshift:alarm:node_metrics_percentage_disk_space_used:2020-04-01 '
'based on PercentageDiskSpaceUsed metric and check OK status.')
def test_node_metrics... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import fvcore.nn.weight_init as weight_init
from torch import nn
import torch.nn.functional as F
from detectron2.layers import Conv2d, FrozenBatchNorm2d, get_norm, BatchNorm2d
from detectron2.modeling import BACKBONE_REGISTRY, ResNet, make_st... |
# facerec.py
import cv2, sys, numpy, os
import datetime
import urllib.request
import numpy as np
size = 4
haar_file = 'haarcascade_frontalface_default.xml'
datasets = 'datasets'
print('Training...')
# Create a list of images and a list of corresponding names
(images, labels, names, id) = ([], [], {}, 0)
for (subdirs, ... |
num=int(input("enter value for num:"))
n1,n2=0,1
count=0
if(num<=0):
print("error! needs positive number")
elif(num==1):
print(n1)
else:
while(count<num):
print(n1," " ,end="")
n=n1+n2
n1=n2
n2=n
count+=1 |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 9 16:28:07 2017
@author: ellie
"""
import tensorflow as tf
# Create TensorFlow object called hello_constant
hello_constant = tf.constant('Hello World!')
with tf.Session() as sess:
# Run the tf.constant operation in the session
output = sess.run(hello_constant)... |
from .db import db
from .usersOnTeam import UsersOnTeams
class Team(db.Model):
__tablename__ = "teams"
id = db.Column(db.Integer, nullable = False, primary_key = True)
teamName = db.Column(db.String(50), nullable = False)
users = db.relationship("User", secondary=UsersOnTeams, back_populates="te... |
import os
import copy
import json
import torch
import logging
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from argparse import ArgumentParser
from torch.optim import lr_scheduler
from torchvision import datasets, models, transforms
logging.basicConfig(level=logging.DEBUG,
... |
import sys
infile = open(sys.argv[1], "r")
table = {}
num = 0
count = 0
dists = dict.fromkeys(range(1000), 0)
for line in infile:
if line[0] == '@':
continue
items = line.strip().split("\t")
name = items[0]
pos = int(items[3])
qual = int(items[4])
seq = items[9]
if qual < 40:
... |
import os, re
import pandas as pd
from functools import reduce
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import f1_score, accuracy_score
from sklearn.metrics import precision... |
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///mybase2.db')
db_session = scoped_session(sessionmaker(bind=engine))
Base = declarative_base()
Base.query = db... |
import math
import numpy as np
import pandas as pd
from scipy.stats import norm
import matplotlib.pyplot as plt
ace_list = {1:'depress', 2:'alcoabuse', 3:'drugabuse', 4:'prison',
5:'patdivorce', 6:'phyabuse1', 7:'phyabuse2', 8:'verbalabuse',
9:'sexabuse1', 10:'sexabuse2', 11:'sexabuse3', 12:... |
import os
# root path of the project
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
# directory for logs
LOG_DIR = os.path.join(ROOT_DIR, 'backend', 'logs')
# dir for all configs
CONFIGS_DIR = os.path.join(ROOT_DIR, 'configs')
# path of the config file for connection to postgresql
DATABASE_CONFIG_PATH = os.p... |
'''
Created on 22.10.2014
@author: Philip
'''
from data import db
import users.constants
class CRUDMixin(object):
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True)
@classmethod
def create(cls, commit=True, form=None, **kwargs):
instance = cls(**kwargs)... |
#!/usr/bin/env python
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
def main():
driver = webdriver.Remote(
command_executor='http://127.0.0.1:8910',
desired_capabilities=DesiredCapabilities.PHANTOMJS)
driver.get('https://citrix.se... |
import copy
import numpy as np
from nanodet.data.transform.warp import (
ShapeTransform,
get_flip_matrix,
get_perspective_matrix,
get_rotation_matrix,
get_scale_matrix,
get_shear_matrix,
get_stretch_matrix,
get_translate_matrix,
warp_and_resize,
)
def test_get_matrix():
# TOD... |
from flask import Flask, render_template, request
from data import Book, BOOK_TYPES
import json
app = Flask(__name__)
@app.route("/")
def index():
return render_template(
"index.html",
**{"greeting": "Welcome!", "book_types": BOOK_TYPES.keys()}
)
@app.route("/charges", methods=["POST"])
def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.