text stringlengths 38 1.54M |
|---|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main.ui'
#
# Created by: PyQt5 UI code generator 5.13.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets, Qt
import glob
import os
import sys
import core
import csv
class Ui_Form(QtWidget... |
def my_func():
def g(a, b):
return a - b
x = 1
y = 2
g(x, y)
# Please call g again with the argument order reversed
# END OF CONTEXT
g(y, x)
# END OF SOLUTION
def check(candidate):
import inspect
source = inspect.getsource(candidate)
lines = source.strip().split... |
# Generated by Django 3.1.3 on 2020-11-17 12:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('base', '0014_auto_20201117_1745'),
]
operations = [
migrations.AlterField(
model_name='teacher',
name='Teacher_code'... |
from entities import *
#testing module vars
#print(a)
class player:
def player_levelling():
starting_level = 1
max_level = 100
pass
pass |
#!/usr/bin/env python3
""" Keras """
import tensorflow.keras as K
def build_model(nx, layers, activations, lambtha, keep_prob):
"""builds a neural network with the Keras library
Args:
nx is the number of input features to the network
layers is a list containing the number of nodes in each lay... |
from helpers import data_loader as dl
import numpy as np
# from lstm_optimizer import do_optimize
from ensemble_optimizer import do_optimize
from helpers.email_notifier import notify
save_data = False
load_data = False
look_back = 32
def optAndNotify(data, labels):
try:
do_optimize(2, data, labels)
fi... |
import argparse
import cStringIO
import errno
import itertools
import json
import os
import re
import shutil
import sys
import zipfile
import bs4
import requests
BASE_URL = 'http://www.mathworks.com/matlabcentral/fileexchange'
TAG_REGEX = re.compile(r'([\w\s]+)(?:\(\d+\))?')
def http_get(*args, **kwargs):
if 't... |
# ONLY EDIT FUNCTIONS MARKED CLEARLY FOR EDITING
import numpy as np
# modify this function, and create other functions below as you wish
def question01(portfolios):
answer = 0
# need to optimise lots, dont go over same numbers etc.
for p1 in portfolios:
for p2 in portfolios:
total = p1 ^ p2
... |
#!/usr/bin/python
import os
import speedtest
from Logger import CliLogger
class SpeedtestClass:
def __init__(self, logger):
self.servers = []
self.logger = logger
self.speedtest = speedtest.Speedtest()
self.init_servers()
def init_servers(self):
self.logger.log("Getting... |
from StringIO import StringIO
import math
import unittest
from table import Table, Row
class TableTest(unittest.TestCase):
def testBasic(self):
table = Table(['a', 'b'])
row = table.add_row([1, 2])
self.assertEquals((1, 2), (row['a'], row['b']))
self.assertEquals((1, 2), (row.a, ro... |
def square_root_bi(x, epsilon):
"""Bi-section solution"""
assert x >= 0, 'x must be non-negative, not' + str(x)
assert epsilon > 0, 'epsilon must be positive, not' + str(epsilon)
low = 0
high = max(x, 1.0)
guess = (low + high) / 2.0
ctr = 1
while abs(guess ** 2 - x) > epsilon and... |
"""
BASICS
Calculates the finite difference coefficients for a single variable
"""
from math import factorial
import numpy as np
# Number of coefficients needed
# m (int): Derivative
# n (int): Accuracy
def coefficient_number(m, n):
return 2*((m+1)//2) -1 +n
# Finds the middle point of a list with a guarant... |
from __future__ import absolute_import
from ultron8.exceptions import UltronPluginException
class PluginLoadError(UltronPluginException):
pass
class IncompatiblePluginException(UltronPluginException):
pass
|
# Copyright (c) Jeremías Casteglione <jrmsdev@gmail.com>
# See LICENSE file.
import bottle
from pytest import raises
from _sadm.devops.wapp.auth import auth
from _sadm.devops.wapp.auth.error import AuthError
from _sadm.devops.wapp.user import WebappUser
def test_login_config(devops_wapp):
wapp = devops_wapp('auth'... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# *****************************************************************************
# МОДУЛЬ: -
# ФАЙЛ: SMARTHOMEONE.PY
# ЗАГОЛОВОК: ФАЙЛ ПРОГРАММЫ
# ОПИСАНИЕ: -
# *****************************************************************************
import os
import sys
impo... |
import cv2, numpy as np
cap = cv2.VideoCapture('./opencv/samples/data/vtest.avi')
# 3 Background Subtractor
#fg_bg = cv2.bgsegm.createBackgroundSubtractorMOG()
#fg_bg = cv2.createBackgroundSubtractorMOG2(detectShadows=False)
fg_bg = cv2.createBackgroundSubtractorKNN(detectShadows=False)
while cap.isOpened():
ret,... |
import pytest
from aiohttp.test_utils import make_mocked_request
from aiohttp.web import json_response
from aegis import middlewares
from aegis.exceptions import AuthException
from asynctest import CoroutineMock
async def test_auth_middleware_checks_aiohttp_auth_initialization():
# make a mock request
stub_re... |
from testdata.put_user import put_user_url_code as pc ,put_user_url_data as pd
import allure
@allure.step('PUT Method Code')
def test_put_user_response_code():
assert pc == 200
@allure.step('create user name check')
def test_put_user_data():
assert pd["name"] == "adminuser" and pd["job"] == "Admin"
|
import datetime, time
import logging
from sets import ImmutableSet
from google.appengine.ext import db
from twitter.api import TwitterApi
import context, deploysns
from common.utils import url as url_util, timezone as ctz_util, klout as klout_util
from common.dateutil.parser import parser as datetime_parser
from comm... |
# Input: amount = 5, coins = [1, 2, 5]
# Output: 4
# Explanation: there are four ways to make up the amount:
# 5=5
# 5=2+2+1
# 5=2+1+1+1
# 5=1+1+1+1+1
def coinComb(arr,m,n):
dp = [0] * (n+1)
dp[0] = 1
for coin in arr:
for x in range(coin,n+1):
dp[x] += dp[x-coin]
return dp[n]
arr = ... |
from src.k_means.main import generate_k_points, assign_points, update_centers
def test_generate_k_points(prepared_fixed_points):
k_points = generate_k_points(prepared_fixed_points, 10)
assert len(k_points) == 10
def test_assign_points(prepared_fixed_points):
assignments = assign_points(prepared_fixed_... |
"""This is a Sudoku Puzzle Solver that will take a sudoku puzzle represented as an array of arrays where empty cells
are represented as 0's and output the sudoku puzzle with all empty cells filled in correctly
Example input:
puzzle = [[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9,... |
class Solution:
def reverse(self, x: int) -> int:
#get absolute value of x, strip and reverse it
n = str(abs(x))
n = n.strip()
n = n[::-1]
#store results in output as int
output = int(n)
#costrains
if output >= 2** 31 -1 or o... |
import time
from extract_feature import BertVector
bv = BertVector()
print(bv.encode(['今天天气不错']))
for i in range(10):
tt = input()
lis= [str(tt)]
#print(lis)
t1 = time.time()
sk = bv.encode(lis)
t2 = time.time()
print(int(round(t2 * 1000))-int(round(t1 * 1000))," ms") |
"""
Utilities to manage randomness in LensKit and LensKit experiments.
"""
import warnings
import zlib
import numpy as np
import random
import logging
import seedbank
_log = logging.getLogger(__name__)
derive_seed = seedbank.derive_seed
def get_root_seed():
"""
Get the root seed.
Returns:
nump... |
import webapp2
import string
import jinja2
import os
from gm.gmgoto import GmGoto
from gm.gmrsvp import GmRsvp
from gm.gmoneclick import GmOneClick
from gm.gmreview import GmReview
from ya.yaxml import YaXML
from ya.yabutton import YaButton
class GmActionsHandler(webapp2.RequestHandler):
def __init__(self, request... |
# coding=utf-8
import unittest
import os
from time import sleep
from macaca import WebDriver
import public.methods as t
import public.case_xls as xl
class IOSSDK(unittest.TestCase,t.Methods,xl.Case_xls):
def setUp(self):
self.driver = WebDriver(self.desired_caps(), self.server_url())
self.driver.init()
self.case... |
from svgwrite.text import Text
from ...types import PageProperties, ScoreSheet, StaffProperties
def markup_title(page_prop: PageProperties, staff_prop: StaffProperties, sheet: ScoreSheet):
# TODO calc real text width and heights
title_height = 100
# TODO calc real text width and heights
author_title... |
import json
number = json.load(open('/root/term_paper_2/articles/numbers.json', 'r'))
for key, value in number.items():
total = 0
for value2 in value.values():
total += int(value2)
print(key, ' is ', total)
number[key][key + 'total'] = total
json.dump(number, open('/root/term_paper_2/articles... |
import cv2
image = cv2.imread('1.png')
mask = cv2.imread('mask.png')
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
ROI = image[y:y+h, x:x+w]
... |
1. Let _R_ be the *this* value.
1. If Type(_R_) is not Object, throw a *TypeError* exception.
1. If _R_ does not have an [[OriginalFlags]] internal slot, throw a *TypeError* exception.
1. Let _flags_ be the value of _R_'s [[OriginalFlags]] internal slot.
1. If _flags_ c... |
#사전
#순서 없고, key-value 매칭 자료형
#len(),in,not in 정도만 가능하다
#사전 만들기
d=dict() # 빈 사전
print(d,type(d))
#방법 2 : {} 를 이용하여 만들기
d={}
print(d,type(d))
#방법 3 : key-value ang 를 이용하여 만들기
d=dict(one=1, two = 2 )
print(d,type(d))
#방법 4 : key, value 리스트들이 따로 있을때
#zip 함수를 이용한다
keys={"one","two","three"}
values={1,2,3,}
d=dict(z... |
import json
from Status import *
class StatusEncoder(json.JSONEncoder):
"""An encoder of status.
"""
def default(self, o):
"""The default method for the encoding.
Args:
self: the encoder.
o: an object to encode.
"""
if isinst... |
#-*-coding: utf-8-*-
'''
2). Отсортируйте по возрастанию методом слияния одномерный вещественный массив, заданный случайными числами на
промежутке [0; 50). Выведите на экран исходный и отсортированный массивы.
'''
import random
def merge(left, rigth):
sort_list = []
left_idx = rigth_idx = 0
left_len, rigth... |
# Generated by Django 2.0.10 on 2019-01-27 09:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('structure', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Gameweek',
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2002-2013 Infrae. All rights reserved.
# See also LICENSE.txt
import Acquisition
from five import grok
from zope.interface import Interface, Attribute
from zope.schema.interfaces import IContextSourceBinder
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
from s... |
from collections import deque
n,m=map(int,input().split(' '))
dq=deque()
dq.append(n)
visit=[0 for i in range(1000001)]
result=0
visit[n]=visit[n]+1
while dq:
node=dq.popleft()
dx=[node+1,node-1,node*2]
for i in dx:
if 0<=i<=100000 and visit[i]==0:
dq.append(i)
visit[i]=visi... |
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.models import User
from django.shortcuts import render, get_object_or_404
# Create your views here.
from django.views import generic
... |
#!/usr/bin/env python
"""Convolutional network example.
Run the training for 50 epochs with
```
python __init__.py --num-epochs 50
```
It is going to reach around 0.8% error rate on the test set.
"""
from __future__ import print_function
import sys
import logging
import numpy
import os
import subprocess
from argpars... |
# -*- coding: utf-8 -*-
# -*- mode: python -*-
import os
import pycurl
from adispatch import adispatch
from .other import encode_dict
from .special import *
NoneType = type(None)
class NetError(Exception):
def __init__(self, ec, *args, **kvargs):
self.ec = ec
super().__init__(*args, **kvargs)
cla... |
import pandas as pd
from InternetScraper.WebCrawler import WebCralerSearch
from InternetScraper.ScrapeVideo import ScrapeVideos
from WordUtils.Utils import Utils
from datetime import datetime
from collections import defaultdict
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
... |
def sqrt(n):
approx = n/2.0 # Start with some or other guess at the answer
while True:
better = (approx + n/approx)/2.0
if abs(approx - better) < 0.001:
return better
print(better)
approx = better
print(sqrt(25.0))
|
import logging
from telethon import events
from peano import measured
from ...settings import admin
def handle_private_message(client) -> None:
""" Forward private messages to admin
"""
log = logging.getLogger('private')
@events.register(events.NewMessage(outgoing=False))
@measured()
async d... |
# -*- coding: utf-8 -*-
from mod_python import apache, Session, util as modutil
from xml.dom import minidom, Node
import os
import sys
resurssit = "/nashome3/saelosmo/html/tiea218/teht4"
sys.path.append(resurssit)
import dom_utils as domutil
htmlpath = os.path.join(os.path.join(resurssit, "templates"), "logout.xhtml... |
"""
This type stub file was generated by pyright.
"""
import vtkmodules.vtkCommonExecutionModel as __vtkmodules_vtkCommonExecutionModel
class vtkProbePolyhedron(__vtkmodules_vtkCommonExecutionModel.vtkDataSetAlgorithm):
"""
vtkProbePolyhedron - probe/interpolate data values in the interior,
exterior or of... |
import sys
import random
import string
from ..session_status import *
import tkinter as tk
class DummyUser:
def __init__(self):
self.name = "John " + "".join(
random.choice(string.ascii_uppercase) for i in range(10)
)
self.id = random.randint(0, 100)
self.position = "1... |
# this python/scons script implements Agency's build logic
# it may make the most sense to read this file beginning
# at the bottom and proceeding towards the top
import os
def create_a_program_for_each_source_in_the_current_directory(env):
"""Collects all source files in the current directory and creates a progra... |
#!/usr/bin/env python2
import sys
import random
import copy
from itertools import combinations
import Queue as queue
# Dice 1,Dice 2,Dic... |
def sqr(item):
return item * item
l1 = [1,2,3,4,5]
l2 = [6,7,8,9,10]
# for i in l1:
# print(sqr(i))
# s = map(sqr, l1)
# s = map(lambda x: x+2, l1)
def add(a, b):
return a+ b
# print(list(map(add, l1, l2)))
a = ["1", "2", "3", "4"]
# b = "1"
# print(int(a[0]))
print(a)
print(list(map(int, a)))
# pr... |
__author__ = 'Hk4Fun'
__date__ = '2018/10/2 17:59'
'''题目描述:
Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");... |
Input = input().split()
print("TRIANGULO: {0:.3f}".format(float(Input[0]) * float(Input[2]) * 0.5))
print("CIRCULO: {0:.3f}".format(float(Input[2])**2 * 3.14159))
print("TRAPEZIO: {0:.3f}".format((float(Input[0]) + float(Input[1])) * float(Input[2]) / 2))
print("QUADRADO: {0:.3f}".format(float(Input[1])**2))
print("RET... |
import random
import string
import time
from datetime import date, timedelta
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.... |
LEARNING_RATE_BASE = 0.1
LEARNING_RAGE_DECAY = 0.99
LEARNING_RAGE_STEP = 1
global_step = tf.Variable(0, trainable=False)
learning_rate = tf.train.exponential_decay(LEARNING_RATE_BASE,
global_step, LEARNING_RATE_STEP, LEARNING_RATE_DECAY,
stairecase=True)
w = tf.Variable(tf.constan(5, dtype=tf.float3... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 20 17:03:43 2018
@author: fzhan
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
from sklearn.model_selection import train_test_split
data=pd.read_csv('CF_data.csv',index_col=0)
data0=pd.read_csv('yelp_business.csv')... |
import sympy
import re
NORMAL = 1
FORMULA = 2
def get_type(s):
if re.search('[a-z]+', s) is not None:
return FORMULA
else:
return NORMAL
# 替换数学符号
def special_char(s):
s = str.replace(s, ' ', '')
s = str.replace(s, '×', '*')
s = str.replace(s, r'\times', '*')
s = str.replace(... |
# ---
# jupyter:
# celltoolbar: Create Assignment
# jupytext:
# cell_metadata_filter: all
# notebook_metadata_filter: all
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.2'
# jupytext_version: 1.0.0-rc2
# kernelspec:
# display_name: Pytho... |
from django.shortcuts import get_object_or_404, render
from django.db.models import Sum
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
from django.http import HttpResponse
import json
from django.template.load... |
from django.urls import path
from . import views
urlpatterns = [
# base urls & profile
path('', views.home, name='home'),
path('profile/profile/', views.profile, name='profile'),
path('profile/photos/', views.photos_index, name='photos_index'),
# home urls
path('homes/create/', views.Create_Ho... |
import asyncio
import datetime
import json
import logging
import random
import dateutil.parser
import pytz
import irc.client
import sqlalchemy
import common.http
import common.time
import common.storm
import lrrbot.decorators
from common import googlecalendar
from common import utils
from common.config import config
... |
# -*- coding, utf-8 -*-
import sys
from numpy import exp, log, sqrt
from numpy import inf
from scipy.stats import norm, lognorm
from scipy.special import jv
from scipy.integrate import quad
from scipy.optimize import newton
from scipy.optimize import brentq
## number of constant
CONST_TOLERANCE_MASTER = sy... |
#!/bin/python3
import sys
h = int(input().strip())
m = int(input().strip())
time={
'0':'o\' clock','1':'one','2':'two','3':'three','4':'four',
'5':'five','6':'six','7':'seven','8':'eight','9':'nine','10':'ten',
'11':'eleven','12':'twelve','13':'thirteen','14':'fourteen','15':'quarter',
'16':'sixteen','17':'seve... |
import distro, utils, random
def _solver(stats):
(mu, sig2) = distro.extractStats(stats, [distro.Stat.Mu, distro.Stat.Sig2])
roots = utils.solve_quadratic_eqn(1, -2 * mu - 1, mu ** 2 + mu - 3 * sig2)
if roots == None:
return None
else:
a = min(roots)
b = 2 * mu - a
retur... |
import copy
class Layer():
def __init__(self, width, height, name, default=None, offset_x = 0, offset_y = 0, render_hint=None):
self.width = width
self.height = height
self.name = name
self.offset = (offset_x, offset_y)
self.reset(default=default)
self.render_hint =... |
'''
https://leetcode.com/problems/swap-for-longest-repeated-character-substring/
'''
class Solution:
def maxRepOpt1(self, text: str) -> int:
pass
class Solution_BruteForce:
def maxRepOpt1(self, text: str) -> int:
textArr = list(text)
maxLen = 0
for i in range(len(textArr)-1):
... |
from collections import deque
import sys
with open("log.txt") as file:
[last_line] = deque(file, maxlen=1) or ['']
errors = last_line.split('ERROR SUMMARY: ')[1]
errors_count = int(errors.split(' errors')[0])
if errors_count:
sys.stderr.write("Errors founded by valgrind: {0}\n".format(errors_co... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
import os
# self defined packages
from ...backbone_models.resnet.resnet import resnetSelection... |
def RulesAgent( observation, configuration, verbose=True ):
verbose = True
try:
from functools import lru_cache
from itertools import product
from typing import Union, List, Tuple, FrozenSet, Set
from collections import defaultdict
import numpy as np
import random... |
import torch
import numpy as np
import torch.nn.functional as F
import torch.optim as optim
from deeprobust.graph.defense import GCN
from deeprobust.graph.global_attack import DICE
from deeprobust.graph.utils import *
from deeprobust.graph.data import Dataset
import argparse
parser = argparse.ArgumentParser()
parser.... |
import numpy as np
from scipy.optimize import minimize
def mae_loss(X, y, coeff, w=None):
pred = np.dot(X, coeff)
if w is not None:
return np.mean(np.abs(pred - y) * w)
else:
return np.mean(np.abs(pred - y))
def mae_regression(X, y, w=None):
def wrapper(coeff):
return np.array(mae_loss(X, y, coeff... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from PIL import Image
import random
max_iters = 6000
batch_size = 100
learning_rate = 3e-4
(nxtrain, nytrain), (nxtest, nytest) = tf.keras.datasets.mnist.load_data()
nxtrain =... |
import torch
from torch import nn
from torch.autograd import Variable
from copy import deepcopy
from inflated_inception_unet import *
from inflated_inception_rgb import *
import config
class InceptionAttention(nn.Module):
def __init__(self):
super(InceptionAttention, self).__init__()
config.USE_FL... |
import os, re, codecs, subprocess
import shutil, stat, errno, sys, operator
import urllib.parse, html
from lxml import etree
ref_path = 'e:/tools/wget/cplusplus_reference/www.cplusplus.com/'
full_site = False
web_ref_prefix = 'http://www.cplusplus.com/reference/'
qch_proj_name = 'qch-proj'
ref_dirs = [
'img',
... |
class Stack:
def __init__(self):
self.data = []
self.top = -1
def push(self, n):
self.data.append(n)
self.top += 1
def pop(self):
N = self.data[self.top]
del self.data[self.top]
self.top -= 1
return N
def view(self):
return self.... |
import pymongo
import os
import base64
import datetime
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
import threading
import getpass
import json
import logging
import ast
import time
from urllib import request, parse
import requests
import operator
from queue import Queue
from d... |
# Generated by Django 3.2 on 2021-05-08 13:20
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('JWTAuth', '0004_alter_employee_start_work_date'),
]
operations = [
migrations.AlterField(
model_name='employee',
... |
import numpy as np
def kvol3d(rs):
"""Volume of reciprocal state per electron in 3D (unpolarized)
Args:
rs (float): Wigner-Seitz density parameter
Return:
float: kvol
"""
kvol = (2*np.pi)**3/(4*np.pi*rs**3/3)
return kvol
def ntsum_raw3d(kvecs, nkm, kvol, nke=None):
""" Calculate momentum distri... |
import os
import time
import random
import string
import urllib.parse
from ftplib import FTP
from flask import Flask, jsonify, render_template, request, url_for, send_from_directory
from flask_socketio import SocketIO, send, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = "sgsdgJHUIHHAasfasUDN"
socketio = Socket... |
''' Present an interactive function explorer with slider widgets.
Scrub the sliders to change the properties of the ``sin`` curve, or
type into the title text box to update the title of the plot.
Use the ``bokeh serve`` command to run the example by executing:
bokeh serve sliders.py
at your command prompt. Then nav... |
# Special ALT Characters
# http://www.tedmontgomery.com/tutorial/altchrc-a.html
import os
import configparser
import pygame
import numpy as np
from .color import colornames
from .util import check_divisibility
class Curses():
def __init__(self, screen_width, screen_height, color):
self.screen_width =... |
#!/usr/bin/env python
# coding: utf-8
# In[9]:
import pandas as pd
import numpy as np
import math
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
import itertools
from sklearn.preprocessing import LabelBinarizer, LabelEncoder
from sklearn.metrics import accura... |
from django.core.management.base import BaseCommand, CommandError
from datetime import date, timedelta
# from parse.models import *
class Command(BaseCommand):
help = 'parses input .CSV for Dynamics Import (Luna)'
def add_arguments(self, parser):
parser.add_argument('in_csv', type=str)
parser.... |
from contradiction.medical_claims.token_tagging.problem_loader import AlamriProblem, load_alamri_problem
from typing import List, Iterable, Callable, Dict, Tuple, Set
from cpath import output_path
from misc_lib import path_join
def save_as_text():
problems: List[AlamriProblem] = load_alamri_problem()
save_pa... |
from invoke import task
@task
def clean(ctx):
"""Remove virtual environement"""
ctx.run("pipenv --rm", warn=True)
@task
def init(ctx):
"""Install production dependencies"""
ctx.run("pipenv install")
@task
def init_dev(ctx):
"""Install development dependencies"""
ctx.run("pipenv install --d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import urllib2
import csv
def lerCsv(inFile,outFile):
csvIn = open(inFile)
csvOut = open(outFile,'w')
fieldNames = ['title', 'abstract', 'keywords', 'doi', 'url', 'bibtex']
reader = csv.DictReader(csvIn)
writer = csv.DictWriter(csvOut, fieldnames=fieldNames... |
from random import randint
num = (randint(0, 10), randint(0, 10), randint(0, 10),
randint(0, 10), randint(0, 10))
print(f'Os valores sorteados foram: ', end = '')
for numero in num:
print(f'{numero} ', end = '')
print(f'\nO maior valor foi: {max(num)}')
print(f'O menor valor foi: {min(num)}') |
import sys
include_path = r'motion synthesis/'
sys.path.append(include_path)
from randomWalking import *
def main():
try:
input_num = int(raw_input('Please input the steps number : '))
except ValueError:
print "Not a number"
w = randomWalking(input_num)
if __name__ == "__main__":
main()... |
#!/usr/bin/python3
import yaml
import json
import requests
import urllib3
import time
import datetime
import sys
import os
# Search key of fields based on value
def fieldSearch(value):
for k,v in fields.items():
if v == value:
return k
return False
# Don't submit Null/None data
def removeN... |
import RPi.GPIO as GPIO
###################################################################################################
def main():
GPIO.setmode(GPIO.BCM) # use GPIO pin numbering, not physical pin numbering
led_gpio_pin = 23
GPIO.setup(led_gpio_pin, GPIO.OUT)
pwmObject = GPIO.PWM(led_gpio_... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 4 09:55:52 2019
@author: 13669
"""
from datetime import datetime,date
import pickle
class Recording:
cla_cost={'1':'Housing','2':'Clothing','3':'Food','4':'Learning','5':'Internet',
'6':'Pet','7':'Sports','8':'Medical','9':'Travel','10':'Snacks','... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 11 11:50:52 2018
@author: Namish Kaushik
"""
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import scale
from scipy.stats import zscore
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.clus... |
import sys, os
import glob
import cv2
import numpy as np
def contours(path_to_image, subfolder):
try:
os.mkdir('results/'+subfolder)
except Exception as e:
print(e)
pass
img = cv2.imread(path_to_image)
img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # convert to hsv
# min and ... |
# -*- coding: utf-8 -*-
from pyloader import DataReader
from pyloader import Dataset
from pyloader import DataCollator
from pyloader import DataLoader
import json
import torch
# Step 1: Inherit the class `DataReader` and implement the method `read_file()`
class JsonLineDataReader(DataReader):
"""Data reader for re... |
# 数据库配置文件
config = {
'driver': 'mysql',
'host': '12313',
'port': 3306,
'database': '', # 数据库名字
'username': '', # 数据库用户名
'password': '', # 数据库密码
'prefix': ''
}
|
import os,sys
sys.path.append(os.getcwd())
import time
from collections import deque
def print_helloWorld():
print("Hello, World!")
def stringTest():
word = '字符串'
sentence = "这是一个句子。"
paragraph = """这是一个段落,可以由多行组成"""
str = 'Runoob'
print("输出字符串",str) # 输出字符串
print("输出第一个到倒... |
from typing import List
class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
lookup = {}
for count_domain in cpdomains:
cd = count_domain.split(" ")
count = int(cd[0])
domains = cd[1].split(".")
for i in range(len(d... |
# -*- coding: utf-8 -*-
"""
This script is used to perform post-hoc analysis and visualization:
the classification performance of subsets (only for Schizophrenia Spectrum: SZ and Schizophreniform).
Unless otherwise specified, all results are for Schizophrenia Spectrum.
"""
#%%
import sys
sys.path.append(r'D:\My_Code... |
import logging
def init():
# Configure logging (https://docs.python.org/3/library/logging.html#logrecord-attributes)
FORMAT = '%(asctime)s %(levelname)s %(name)s %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT)
def get(name):
return logging.getLogger(name)
init() |
import torch
import torch.nn as nn
import torch.nn.functional as F
from third_party.cove.cove import MTLSTM
class BASE(nn.Module):
def __init__(self, args, data):
super(BASE, self).__init__()
self.args = args
if args.model == 'cove':
self.cove = MTLSTM(n_vocab=args.word_voca... |
# 商品列表
import json
goods = [
{"name": "手机", "price": 1999},
{"name": "耳机", "price": 100},
{"name": "键盘", "price": 200},
{"name": "美女", "price": 998},
{"name": "媳妇", "price": 2998},
{"name": "电脑", "price": 5998}
]
with open('goods_file','w') as f :
f.write(json.dumps(goods)) |
import subprocess
import pickle
import os
import sys
import pdbfixer
import simtk
from simtk.openmm.app import PDBFile
"""
psuedocode overview:
import pdb
count chains
remove all but first chain
find missing residues
add missing residue dict to list to writeout later
add missing atoms
w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.