text stringlengths 8 6.05M |
|---|
import maya.cmds as cmds
def rotateImage(objName, deg):
for x in range(0, 360/deg):
l = 'x'+str(x) + 'y0' + 'z0'
cmds.xform(objName, relative=True, translation=(deg, 0, 0) )
screenShot(objName, l)
def screenShot(objName, l):
ws = 'D:\\test'
wsp = ws + "/" + "images"... |
def digit_sum(n):
sum = 0
for i in str(n):
sum = sum + int(i)
return sum |
import sys, os
sys.path.insert(0, '../vision/')
sys.path.append('../')
from pytorch_segmentation_detection.datasets.pascal_voc import PascalVOCSegmentation
import pytorch_segmentation_detection.models.fcn as fcns
import pytorch_segmentation_detection.models.resnet_dilated as resnet_dilated
from pytorch_segmen... |
from unittest import TestCase
from sorting import *
LIST_ONE = [1, 2, 3, 4, 5]
LIST_TWO = [5, 4, 3, 2, 1]
LIST_THREE = [3, 8, 1, 5, 2, 1, 13, 0]
SORTED_LIST_ONE = LIST_ONE[:]
SORTED_LIST_TWO = SORTED_LIST_ONE[:]
SORTED_LIST_THREE = [0, 1, 1, 2, 3, 5, 8, 13]
class MergeSortTests(TestCase):
def test_sort_1(self... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#importing data set
dataset = pd.read_csv('breast_cancer.csv')
x = dataset.iloc[:,1:-1].values
y = dataset.iloc[:,-1].values
#split dataset
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = trai... |
# Реализуйте методы activation и summatory класса Neuron. Когда вы начнёте решать задачу, вам нужно будет просто скопировать соответствующую функцию, которую вы написали в ноутбуке (без учёта отступов; шаблон в поле ввода ответа уже будет, ориентируйтесь по нему). Сигнатура функции указана в ноутбуке, она остаётся неиз... |
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#############################################################################################
# #
# check_prev_getnrt_process.py: kill getnrt process if the pr... |
class _PipeMeta(type):
def __new__(typ, *args, **kwargs):
import ipdb; ipdb.set_trace()
return super(_PipeMeta, typ).__new__(typ, *args, **kwargs)
class Pipe(object):
__metaclass__ = _PipeMeta
def __new__(cls, *args, **kwargs):
import ipdb; ipdb.set_trace()
return super(P... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
import OpenGL.GL as gl
import itertools
#local imports
from common import SETTINGS, COLORS, VSYNC_PATCH_HEIGHT_DEFAULT,\
VSYNC_PATCH_WIDTH_DEFAULT
class VsyncPatch_Version1:
def __init__(self, left, bottom, widt... |
'''
Created on Nov 25, 2014
@author: Idan
'''
if __name__ == '__main__':
pass
'''
P = number of samples
K1 =number of clusters
Iter1=number if itterations to finish
S=times of reexecution
'''
from k_mean_module import create_test_set1,my_k_means,plot_results,create_test_set2
P = 8000
K1 =4
Iter1=100
S=1
x1=... |
"""Modoboa - Mail hosting made simple."""
from pkg_resources import DistributionNotFound, get_distribution
try:
__version__ = get_distribution(__name__).version
except DistributionNotFound:
# package is not installed
pass
def modoboa_admin():
from modoboa.core.commands import handle_command_line
... |
# -*- coding: utf-8 -*-
'''测试python方法重名的情况'''
#python中没有方法的重载,定义多个同名的方法,只有最后一个有效。
class Person:
def say_hi(self):
print("hello!")
def say_hi(self,name):
print("{0},hello".format(name))
p1 = Person()
#p1.say_hi() #运行报错。TypeError: say_hi() missing 1 required positional argument: 'name'
p1... |
from datetime import datetime
import MySQLdb
import configparser
import logging
logging.basicConfig(handlers=[logging.FileHandler('/var/www/pow/pow.log', 'a', 'utf-8')],
level=logging.INFO)
# Read config and parse constants
config = configparser.ConfigParser()
config.read('/var/www/pow... |
from __future__ import print_function
import tensorflow as tf
import numpy as np
from src.main.utils.decorators import lazy_property
from src.main.dataset.datasets import Datasets
class Config:
"""Holds model hyperparams and data information.
The config class is used to store various hyperparameters and da... |
import sys
import os
import csv
def isfloat(value):
try:
float(value)
return True
except ValueError:
return False
reu_path = "C:/Users/Daway Chou-Ren/Documents/REU/"
fromDir = sys.argv[1]
toDir = sys.argv[2]
with open(reu_path + fromDir, "rb") as csv_file:
reader = csv.reader(csv_file)
... |
#Group Anagrams
#High Time Complexity
class Solution(object):
def groupAnagrams(self, strs):
res = []
resfreq = []
for s in strs:
freqs = [0]*26
for l in s:
freqs[ord(l)-97] += 1
found = -1
for i in range(len(resfreq)):
... |
# import pandas as pd
# df = pd.read_csv("/home/spaceman/my_work/Most-Recent-Cohorts-Scorecard-Elements.csv")
# df=df[['STABBR']]
# print df['STABBR'].value_counts(normalize=True)
import random
all = ['a', 'b', 'c']
letters = dict(
a = {1:'q', 2:'w', 3:'e'},
b = {1:'f', 2:'g', 3:'h'},
c = {1:'s', 2:'d', 3:... |
#
# Copyright (C) 2020-2030 Thorium Corp FP <help@thoriumcorp.website>
#
from odoo import api, fields, models
# from odoo.modules import get_module_resource
from odoo.exceptions import ValidationError
class ThoriumcorpPatient(models.Model):
_name = 'thoriumcorp.patient'
_description = 'Patient'
_inher... |
from os import listdir
from os.path import isfile, join
class FileNameFeeder:
@staticmethod
def getFiles(inputDir):
onlyfiles = [f for f in listdir(inputDir) if isfile(join(inputDir, f))]
return onlyfiles
@staticmethod
def getImageFiles(inputDir):
fileNameList = FileNameFeeder.... |
#상속 : 기존 클래스를 변경하지 않고 기능을 추가하거나 기존 기능을 변경하여 사용할때 사용
#개발기간을 단축하거나 코드의 중복을 피할 수 있다.
#SmartTv를 만들고 싶어 => 기존의 Tv클래스를 상속받아서 기능을 추가하면 SmartTv
class Tv: #부모클래스, 수퍼클래스
def powerOn(self):
print("TV를 켭니다.")
def powerOff(self):
print("TV를 끕니다.")
class SmartTv(Tv): #자식클래스, 서브클래스
def settopOn(... |
import unittest
from katas.kyu_7.eighties_kids_5_you_cant_do_that_on_tv import bucket_of
class BucketTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(bucket_of('wet water'), 'water')
def test_equals_2(self):
self.assertEqual(bucket_of('slime water'), 'sludge')
def te... |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 3 17:38:40 2018
@author: srikant nayak
"""
from PIL import Image
import pywt
import numpy as np
import matplotlib.pyplot as plt
img1 = Image.open('s1.gif').convert('L')
img2 = Image.open('ss2.gif').convert('L')
img1_ary = np.array(img1)
img2_ary = np.array... |
# num1=int(input('enter the number'))
# num2=int(input('enter the number 2'))
# div=None
# try:
# div=num1/num2
# print('try runs')
# except:
# print('exection ocuured')
# print('continue execution')
# if div!=None:
# print('result:',div)
import traceback,sys
#Types of error
#1. Compile time error
#2.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import vizdoom as vzd
from tabulate import tabulate
from warnings import warn
MAX_MAP = 5
MAX_PLAYERS = 8
MAX_TIMELIMIT = 999
DEFAULT_TIMELIMIT = 10
DEFAULT_WAD_FILE = "cig2017.wad"
FRAMERATE = 35
if __n... |
import codecs
import openpyxl
import sys, os
from time import gmtime, strftime
from pathlib import Path
from openpyxl.utils import get_column_letter, column_index_from_string
import array as arr
import numpy as np
new_old = 1
#excel = "C:/Users/daccl.hy/Desktop/1.xlsx"
excel = "D:/temp.xlsx"
source_name = ''
function... |
#!/usr/bin/python
"""
This is the code to accompany the Lesson 2 (SVM) mini-project.
Use a SVM to identify emails from the Enron corpus by their authors:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preprocess
### ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('basketball', '0061_player_is_active'),
]
operations = [
migrations.AddField(
model_name='game',
name... |
# -*- coding: utf-8 -*-
import wx
import ukbiobank
class M_AM_B(wx.Frame, ukbiobank.ukbio):
pass
class SelectVariablesFrame(wx.Frame, ukbiobank.ukbio):
__metaclass__ = M_AM_B
def __init__(self, parent, ukb):
super().__init__(parent=parent, title="UKBiobank-tools checkbox")
panel = wx.... |
import PyPDF2
import pytesseract
import os
import sys
from pdf2image import convert_from_path
from PIL import Image
from datetime import datetime
from configparser import ConfigParser
import shutil
settings_file = os.path.abspath(os.path.dirname(sys.argv[0])) + "\\settings.ini"
def check_create_dir(order_... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-11-13 02:17
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('project', '0006_auto_20181113_0914'),
]
operations = [
migrations.Re... |
"""setup.py for cryptarchive"""
from setuptools import setup
setup(
name="cryptarchive",
version="0.1.6",
author="bennr01",
author_email="benjamin99.vogt@web.de",
description="encrypted storage server and client",
long_description=open("README.md").read(),
license="AGPLv3",
keywords="... |
import re
import os
## setting working directory ------------------------------------------------
os.chdir("C:/Users/wooki/Documents/GitHub/pythoncourse2018/day06")
# open text file of 2008 NH primary Obama speech
with open("obama-nh.txt", "r") as f:
text = f.readlines()
## TODO: print lines that do not contain 't... |
# author: Christopher Koch
# date: 05/18/2015
# file: Nussinov.py
#
# topic: RNA, Bioinformatics, dynamic programming, recursion
# decription: the nussinov-algorithm was invented by Ruth Nussinov and it is used to predict RNA secondary structure.
def comparable(a, b):
if a == 'A' and b == 'U':
... |
#!/usr/bin/python
import numpy as np
import pylab as py
from scipy import integrate
from COMMON import nanosec,yr,week,grav,msun,light,mpc,hub0,h0,omm,omv,kpc,mchirpfun,fmaxlso
#I will plot the formulas from DrozEtAl1999 with redshift, and see if the extra terms in the stationary phase approximation explain the amplif... |
from flask import Flask,request,jsonify
import json
import sqlite3
from flask_jwt_extended import create_access_token
from flask_jwt_extended import get_jwt_identity
from flask_jwt_extended import jwt_required
from flask_jwt_extended import JWTManager
app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "maxmaxmaxsu... |
# Write a Python program to get the smallest number from a list
# def smallest(lisofnum):
# return min(lisofnum)
# listofnum = [1,2,3,4,5,6,7,8,9]
# output = smallest(listofnum)
# print(output)
print("-----------------------without inbuilt function -------------------------")
def smallestNum(listofNums):
for... |
# Python Substrate Interface Library
#
# Copyright 2018-2020 Stichting Polkascan (Polkascan Foundation).
#
# 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/LIC... |
class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
x1 = coordinates[0][0]
y1 = coordinates[0][1]
x2 = coordinates[-1][0]
y2 = coordinates[-1][1]
try:
if x2 == x1:
for i in range(1,len(coordinates)-1):
... |
class Customer:
fname = ""
lname = ""
age = 0
def addCart(self):
print("add product to",self.fname,self.lname,self.age," 's cart")
customer1 = Customer()
customer1.fname = "Kosin"
customer1.lname = "Wangdee"
customer1.age = 46
customer1.addCart()
customer2 = Customer()
customer2.fname = "Kwanta... |
import socket
import sys
import struct
import select
# if we are on the compucar this will succeed
# if we are not, we enter debug mode
try:
import driver
DEBUG = False
except ImportError:
DEBUG = True
HOST = "127.0.0.1" if "--local" in sys.argv else sys.argv[1]
PORT = 3000
buff_size = 128
last_recived ... |
__author__ = 'Justin'
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from numpy import mean
# Print Justin and Pablo's User Weights
weights = [0.55, 0.5, 0.55, 0.6000000000000001, 0.55, 0.55, 0.5, 0.45, 0.4, 0.4, 0.45, 0.45, 0.45, 0.5, 0.5, 0.45, 0.45, 0.5, 0.55, 0.55, 0.5, 0.55, 0.5, 0.5, 0.4... |
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com>
# Copyright (c) 2020 Florent Kermarrec <florent@enjoy-digital.fr>
#
# Code adapted from ``usb3_pipe``.
# SPDX-License-Identifier: BSD-3-Clause
""" Code for handling SKP ordered sets on the transmit and receive path.
... |
'''
Created on Feb 6, 2012
@author: bogdan hlevca 995151213
'''
#import numerical Python for Matrix operations
import numpy
import SIMPLE
import linalg
#import the TDMA module
from thomas import *
#import the graphi library
import matplotlib.pyplot as plt
# Create a mesh class that holds a vector of nodes
#Class... |
import csv
import numpy
import matplotlib.pyplot as plt
def plot_all_bars(ranks, acceptance_rates, exported_figure_filename):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
#prices = list(map(int, ranks))
X = numpy.arange(len(ranks))
width = 0.25
ax.bar(X+width, acceptance_rates, width)
... |
#!/usr/bin/env python
import math
from random import choice, randint, sample, random
def random_judgement(old_judgement):
return randint(1, 7)
def random_judgement_offset(old_judgement, d=3):
if random() <= 0.5:
d = -d
return (old_judgement + d - 1) % 7 + 1
def randomize_values(data, p, rfunc=ran... |
import argparse
import os
import json
from utils import send_json_post
_APP_URL = f"http://127.0.0.1:5000/led"
""" Example usage
python send_saved_json_to_app.py --filenam=red_check
"""
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--filename", required=True, type=str)... |
class ExportModelBase:
'''
Clase base para las exportaciones.
'''
@classmethod
def classifyUserData(cls, usersData):
classifiedUsersData = {}
for user in usersData:
classifiedUsersData[user.id] = user
return classifiedUsersData
@classmethod
def exp... |
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns # for beautiful... |
class Solution(object):
def sumsquare(self, n):
sum = 0
while(n > 0):
p = n % 10
sum += p ** 2
n //= 10
return sum
def isHappy(self, n):
"""
https://leetcode.com/problems/happy-number/
could use simple hashmap.
but ... |
import sys
# Dmitry Brant, Apr 2021
arg_id = 1
while arg_id < len(sys.argv):
if "prod-" not in sys.argv[arg_id]:
continue
in_file = open(sys.argv[arg_id], encoding="utf-8")
wiki_name = sys.argv[arg_id].split("-")[1]
out_file = open(wiki_name + "_image_candidates.tsv", mode="w", encoding="ut... |
# -*- coding: utf-8 -*-
import datetime
import requests
import lxml.html
from eust.core import conf
_PAGE_DATE_FORMAT = r"%d/%m/%Y %H:%M:%S"
_VERSION_DATE_FORMAT = r"%Y-%m-%d %H%M%S"
def _get_table_name(row):
link_text = row.xpath("td")[0].xpath("a")[0].text
assert link_text.endswith(".tsv.gz"), link_text... |
from tkinter import *
from tkinter.ttk import Entry,Button,OptionMenu
from PIL import Image,ImageTk
import random
from tkinter import filedialog as tkFileDialog
import os
import time
class Tiles():
def __init__(self,grid):
self.tiles=[]
self.grid=grid
self.gap=None
self.moves=0
... |
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import seaborn as sns
from scipy import stats
from scipy.optimize import fsolve
#simulated data
N = 32768 #Number of data points
m = 2e-12 #1 nanogram
T = 300 #Kelvin
k = 300e-6 #kg/s2
gamma_factor... |
import re
lines = []
with open("inputData.txt", "r") as infile:
for line in infile:
lines.append(line.replace('\n', '').replace('\r', ''))
codeLetters = 0
escapedLetters = 0
for line in lines:
codeLetters += len(line)
escaped = re.escape(line)
escapedLetters += len(escaped) + 2 # + 2 for th... |
#!/usr/bin/env python
# More verbose
import requests
import os
import json
requests.packages.urllib3.disable_warnings()
hostname = os.getenv('vmName')
domain = "cliqrdemo"
fqdn = hostname + "." + domain
network = os.getenv('networkName')
netmask = "255.255.255.0"
gateway = "10.110.5.1"
dns_server_list = "10.100.1.15... |
import SWPlugin
import json
import os
import time
from SWParser import monster_name, monster_attribute
sources = {
1: 'Unknown',
2: 'Mystical',
3: 'Light & Dark',
4: 'Water',
5: 'Fire',
6: 'Wind',
7: 'Legendary',
8: 'Exclusive',
9: "Legendary Pieces",
10: "Light & Dark Pieces"
}
def identify_scroll(id):
... |
# Exercise 1
# To run this program go to the terminal and use the command `python exercise1.py`
print("Welcome to Python")
print('Enter your name:')
x = input()
print('Hello, ' + x)
# TODO:
# Get the users age and determine what year they were born.
# print('How old are you?')
# print('So you were born in' + ... |
import cbmpy
import numpy as np
import os
import sys
import pandas as pd
modelLoc = sys.argv[1]
growthMediumLoc = sys.argv[2]
scriptLoc = sys.argv[3]
proteomicsLoc = sys.argv[4]
resultsFolder = sys.argv[5]
model = cbmpy.CBRead.readSBML3FBC(modelLoc, scan_notes_gpr = False)
growthData = pd.read_csv(growthMediumLoc)
pr... |
# Generated by Django 3.2.8 on 2021-10-12 03:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("product", "0001_initial"),
]
operations = [
migrations.AlterModelOptions(
name="product",
options={"verbose_name": "... |
# Exercício 5.14 - Livro
soma = media = 0
qtd = 0
while True:
num = int(input(f'Digite o {qtd + 1}° número: '))
if num == 0:
break
qtd += 1
soma += num
media = soma / qtd
print('=-=' * 15)
print(f'Quantidade de números informados: {qtd}')
print(f'Soma de todos os valores: {soma}')
print(f'Médi... |
__author__ = 'Justin'
from sklearn.linear_model import LogisticRegression
import os
import json
import networkx as nx
import numpy as np
from GetRouteInfo import routeinfo
persons = ['Justin','Justin2','Pablo']
for person in persons:
# Load Data
cwd = os.getcwd()
folder = os.path.abspath(os.path.join(cw... |
class Problem:
def __init__(self, probId, lines = [], name = 'test', points = [], problemType = 'plot', prompts = [], solution = None, text = '', probType = 'Default'):
self.id = probId
self.lines = lines
self.name = name
self.points = points
self.prompts = prompts
self.solution = solution
self.text = t... |
banco = {} # banco para verificar caso a palavra ja exista
inicio = 0 # demarcar o inicio da substring
maior = 0 # maior substring ate o momento
# s = string qualquer
# enumerate para sabermos onde estamos e termos o valor
for i, v in enumerate(s):
if v in banco: # verifica se a letra ja está no banco
... |
# -*- coding: utf-8 -*-
__author__ = 'Tan Chao'
'''
Python logging module wrapper.
'''
import logging
import logging.handlers as LH
import os
import platform
import sys
import time
import traceback
import types
# Logging Levels
# From high to low
LEVEL_CRITICAL = logging.CRITICAL # 50
LEVEL_ERROR = logging.ERROR ... |
from rooms import Room
class MyMaze(Room):
def __init__ (self, st= None, ex = None):
self.__start = st
self.__exit = ex
self.__current = st
def getCurrent(self):
return self.__current
def moveNorth(self):
if self.getNorth() == None:
return Fa... |
import socket
import sys
from threading import Thread
from time import sleep
class Session:
def __init__(self):
self.client1 = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # open socket
def SocketsConnection(self):
try:
self.client1.connect(("127.0.0.1", 10000)) # open conne... |
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
import tornado.log
import tornado.autoreload
from mainsrv import app
import logging
import os
import sys
print("\033[92mLOCAL WEB SERVER MODE\033[0m" if "local" in sys.argv else None)
tornado.autoreload.s... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 22 20:54:00 2016
@author: mjguidry
"""
import requests, tempfile
url='http://sos.nh.gov/WorkArea/DownloadAsset.aspx?id=28313'
resp = requests.get(url)
tempdir=tempfile.tempdir
tmp_file=tempdir+'/temp_nh.xls'
rep_dir='../'
output = open(tmp_file, 'wb')
output.write(res... |
# Generated by Django 2.0.7 on 2018-07-30 11:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('post_app', '0007_auto_20180730_1433'),
]
operations = [
migrations.AddField(
model_name='comment',
name='comment',
... |
# test 1
# dog类
class Dog:
# __init__()方法必须有,每次实例化类的时候都会执行该方法
def __init__(self, name, age):
self.name = name
self.age = age
# 为属性设置默认值
self.color = 'yellow'
def sit(self):
print(self.name.title() + " now is sitting.")
def roll_over(self):
print(self.nam... |
#coding=utf-8
import os
import sys
import logging
from scrapy.crawler import CrawlerProcess
from scrapy.utils.log import configure_logging
from scrapy.utils.project import get_project_settings
def run(name):
configure_logging(install_root_handler = False)
logging.basicConfig(
filename = 'log/%s.log' ... |
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "vivarium_public_health"
__summary__ = "Components for modelling diseases, risks, and interventions with ``vivarium``"
__uri__ = "https://github.com/ihmeuw/vivarium_public_... |
import os
import random
import string
from bitcoin_acks.database.session import get_url
def generate_secret():
alphanumeric = string.ascii_uppercase + string.ascii_lowercase + string.digits
x = ''.join(random.choice(alphanumeric) for _ in range(32))
return x
class Config(object):
DEBUG = False
... |
import os
import typing
from enum import Enum
import boto3
class CloudwatchHandler:
def __init__(self):
self.namespace = f"dcp-wide-test-{os.environ['DEPLOYMENT_ENV']}"
self._client = boto3.client("cloudwatch", region_name=os.environ['AWS_DEFAULT_REGION'])
def put_metric_data(self,
... |
import pandas
import cv2
from glob import iglob
import os
'''
This script will list full path for training set indexing (ls command not working when list too long, need sequential approach)
'''
source = 'data-cleaning/dataset/crowdhuman-coco-yolo/images/train/'
# make sure destination is empty
destination = 'data-cl... |
from django.core.files.base import ContentFile
from django.core.management.base import BaseCommand
import requests
import kronos
from nba_py.player import PlayerList, PlayerGeneralSplits
from players.models import Player
from teams.models import Team
from seasons.models import Season, PlayerSeason
@kronos.register(... |
import torch
from torch.utils.data import Dataset
from torch.nn.utils.rnn import pad_sequence
import json
from tqdm import tqdm
from collections import defaultdict
import random
def load_data(path):
with open(path, 'r') as f:
for line in f:
yield json.loads(line)
def get_data(data, numerical... |
# Copyright 2014 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 by applicable law or a... |
from arcnagios.ldaputils import LDAPObject
import logging
from inspect import isclass
from utils import lazy_staticmethod
log = logging.getLogger(__name__)
MU_1 = 0
MU_01 = 1
MU_SOME = 2
MU_ANY = 3
MU_MINUS = 4
# TODO. Change to MU_SOME when the infosys is ready for it.
MU_SOME_WIP = MU_ANY
def multiplicity_indicat... |
import pytest
from ...app.models import Question, Answer, Upvote, Downvote
from ...app.schemas.answer import AnswerSchema
from ..factories import UserFactory
@pytest.mark.usefixtures('db', 'user')
class TestQuestion:
"""Test answer model"""
def test_create_answer_and_relationship(self, db, user):
_user_ques... |
import pydensecrf.densecrf as dcrf
import numpy as np
import sys
from skimage.io import imread, imsave
from pydensecrf.utils import unary_from_labels, create_pairwise_bilateral, create_pairwise_gaussian, unary_from_softmax
from os import listdir, makedirs
from os.path import isfile, join
img = imread('00006.jpg')
... |
# KVM-based Discoverable Cloudlet (KD-Cloudlet)
# Copyright (c) 2015 Carnegie Mellon University.
# All Rights Reserved.
#
# THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANT... |
# test for for git
# second comment
|
"""
Write a python lambda expression for calculating sum of two numbers and find out whether the sum is divisible by 10 or not.
Test your code by using the given sample inputs.
Verify your code by using the 2nd sample input(highlighted) given below:
+--------------+---------------------+
| Sample Input | Expected ... |
from flask import Blueprint
bp = Blueprint('xup', __name__)
|
# Least Square Sample
# ========================================
# [] File Name : ls_sample.py
#
# [] Creation Date : December 2017
#
# [] Created By : Ali Gholami (aligholami7596@gmail.com)
# ========================================
#
import matplotlib.pyplot as plt
import numpy as numpy
dataset = numpy.array([[3,5],... |
# -*- coding: utf-8 -*-
"""
#define X 0
#define Y 1
#define Z 2
__device__ __forceinline__ void dot_v_v(float *v1, float *v2,float* ret)
{
*ret = v1[X]*v2[X] + v1[Y]*v2[Y] + v1[Z]*v2[Z];
}
"""
import numpy as np
import pycuda.driver as drv
import pycuda.autoinit
from pycuda.compiler import SourceModule
mod = S... |
"""
author: Lily
date : 2018-08-29
QQ : 339600718
冰雪皇后 Dairy Queen DairyQueen-s
抓取思路:改变参数(城市,关键字)获取不同城市的数据,各种关键字搜索的结果不一样,最后需要去重复
注意:1.有些城市是没有数据,是空,例如北京没有数据,但北京是有很多店的,官网数据不全
2.输入的城市和关键字是省份的话也可以抓到数据,但是不全
3.关键字不通,搜到的数据不一样,city=上海市时,关键字用上海市只搜出来27家,但是用上海搜出来51家。
4.需要用其他不同的关键字搜索,比如:"路","号","店"," 区"
"""
impo... |
from flask_restful import Resource
from auth.manager import refresh_access_token
from flask_jwt_extended import jwt_required
class RefreshAccessToken(Resource):
@jwt_required(refresh=True)
def post(self):
return refresh_access_token()
|
from __future__ import unicode_literals
from django.db import models
from django.forms import ModelForm
class Upload(models.Model):
image = models.ImageField("Image", upload_to="images/")
upload_date=models.DateTimeField(auto_now_add =True)
uuid = 123
# FileUpload form class.
class UploadForm(ModelF... |
#!/usr/bin/env python3
"""
convert Gemini data to HDF5 .h5
For clarity, the user must provide a config.nml for the original raw data.
"""
from pathlib import Path
import argparse
import gemini3d.read as read
import gemini3d.write as write
LSP = 7
CLVL = 6
def cli():
p = argparse.ArgumentParser()
p.add_arg... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import re
import csv
#import numpy as np
#import pandas as pd
def read_data(fname) :
mT = []
mHf = []
for line in open(fname, 'r') :
s = line.rstrip('\r\n')
if 'Time, s; Heat flow, Watt' in s : continue
if '; ' in s :
dat = s.split(';')
... |
#!/usr/bin/python
# Orthanc - A Lightweight, RESTful DICOM Store
# Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
# Department, University Hospital of Liege, Belgium
# Copyright (C) 2017-2020 Osimis S.A., Belgium
#
# This program is free software: you can redistribute it and/or
# modify it under the terms ... |
from sklearn import svm
from numpy import genfromtxt
import matplotlib.pyplot as plt
def read_dataset(filePath,delimiter=','):
return genfromtxt(filePath, delimiter=delimiter)
# use the same dataset
tr_data = read_dataset('tr_server_data.csv')
clf = svm.OneClassSVM(nu=0.05, kernel="rbf", gamma=0.1)
clf.fi... |
import serial, time
from flask import Flask, flash, redirect, render_template, request, url_for
app = Flask(__name__)
app.secret_key = 'super_secret_key'
@app.route('/')
def hello_world():
return "Hello World!"
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name = None):
return render_template('he... |
#Test Python Program
import numpy as np
import sys
class Tic_Tac_Board(object):
''' 3 dimensional numpy array
for playing tic tac toe with additional functionality'''
def __init__(self, player1, player2, default_val=0):
self.board = (np.arange(9).reshape(3,3))
self.default_val= default_val
self.board[:] ... |
def mutate_string(string, position, character):
lists = list(string)
lists[position] = character
return "".join(lists)
string = input()
i, c = input().split()
print(mutate_string(str, int(i), c))
|
"""Zookeeper admin interface.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import socket
import logging
_LOGGER = logging.getLogger(__name__)
def netcat(hostname, port, command):
"""Send 4letter netcat t... |
from itertools import cycle, islice
def chessboard(s):
n, m = (int(a) for a in s.split())
if not n or not m:
return ''
return '\n'.join(islice(cycle(
(''.join(islice(cycle('*.'), m)), ''.join(islice(cycle('.*'), m)))
), n))
|
#!/usr/bin/python3
import sys
import ftplib
def directory_listing(ftp_connection):
lines = []
pwd = ftp_connection.pwd()
ftp_connection.dir(pwd, lines.append)
print("[.] Content of Directory " + pwd)
for line in lines:
print(line)
print("\n")
return
def anonFTP(hostname):
try:
ftp = ftplib.FT... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.