text stringlengths 8 6.05M |
|---|
# Title:
# Filename: .py
# Usage:
# Description:
# Author: Nevan Lowe
# Version: 1.1
# Python Revision: 3.*
# IPython Revision: n/a
# TO DO:
#
#---------------------------------------------------------
import random
from datetime import datetime
startTime = datetime.now()
# creates counters to track wins and loss... |
class error_handler:
"""
manages non-fatal program errors. Errors must be added using errors.add()
Argument should be a string containing the error message.
"""
def __init__(self):
pass
error_cache = ""
def add(self, error):
self.error_cache += "\n"
self.error_cache... |
import random as rn
num=rn.randint(1,6)
count=0
while True:
inp_num=int(input("enter the number: "))
if inp_num == num:
count += 1
print(f"you guessed no {count} attempts" )
break
elif inp_num < num:
print("guessed no is less than actual no")
count+=1
else:
... |
from django.contrib import admin
# Register your models here.
from archives.models import ClassVideo, ClassNote, GroupLink
admin.site.register(ClassVideo)
admin.site.register(ClassNote)
admin.site.register(GroupLink)
|
from flask import Flask, render_template
from flask_mail import Mail, Message
from flaskext.mysql import MySQL
from queries import get_group_email_ids
app =Flask(__name__)
mail=Mail(app)
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'idea.management.system4@gmai... |
# -*- coding: utf-8 -*-
class ObjectView(object):
def __init__(self,d):
self.__dict__ = d
|
a = input().split()
if a[0] == a[3]:
print("F")
else:
print("V")
|
from azure.storage.blob import BlockBlobService
import pandas as pd
import time
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd
import numpy as np
import plotly
import plotly.graph_objs as go
from plotly.offline import plot
import random... |
import json
import textwrap
from typing import Iterable, Mapping, Sequence
from ai.backend.client.output.fields import scaling_group_fields
from ai.backend.client.output.types import FieldSpec
from .base import api_function, BaseFunction
from ..request import Request
from ..session import api_session
__all__ = (
... |
import os
import pickle # 파이썬 자료형의 데이터를 파일에 r/w 하게 해주는 모듈.
import re
import requests
from bs4 import BeautifulSoup
from .data import Episode, Webtoon, WebtoonNotExist
class Crawler:
ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
SAVE_PATH = os.path.join(ROOT_PATH, 'saved_data')
def __init__(se... |
import config
import SocketServer, socket
import threading, time, struct
import logging
class VariableWatch_c(object):
#Class to keep track of variables that are being watched
def __init__(self, v):
self.var = v
self.addr = v.addr
self.change_count = -1 #This makes it so variable will b... |
import pytest
import logging
import sys, os
import eons
import esam
sys.path.append(os.path.join((os.path.dirname(os.path.abspath(__file__))), "data"))
from SimpleDatum import SimpleDatum
def test_datum_creation_via_self_registering():
logging.info("Creating SimpleDatum via self Registration")
# ... |
def men_from_boys(arr):
even, odd = [], []
[even.append(x) if x%2==0 else odd.append(x) for x in set(arr)]
return sorted(even) + sorted(odd,reverse=True)
'''
Scenario
Now that the competition gets tough it will Sort out the men from the boys .
Men are the Even numbers and Boys are the odd
Task
Given ... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from typing import Iterable
from pants.backend.swift.goals import tailor
from pants.backend.swift.target_types import SwiftSourcesGeneratorTarget, Swif... |
from cctpy.baseutils import Vectors, Equal, Debug
import unittest
import numpy as np
class BaseUtilsTest(unittest.TestCase):
def test_equal_float(self):
self.assertTrue(Equal.equal_float(1., 1., 1e-5))
self.assertTrue(Equal.equal_float(np.sqrt(2), np.sqrt(2), 1e-5))
self.assertTrue(Equal.e... |
#-*- coding: utf-8 -*-
from googlefinance.client import get_price_data
import pandas as pd
from datetime import date
stock_list = pd.read_csv('data/krx-list.csv')
stock_code = stock_list.code
# parameter setting
param = {
'q': "005930", # Stock code (ex: "005930": Samsung Electronics)
'i': "86400", # Interva... |
#!/usr/bin/env python
# ----------------------------------------------------------
# aircraft_data MODULE for GlassCockpit procject RJGlass
# ----------------------------------------------------------
# This module handels and stores all aircraft data, and communicated via Simconnect to FSX
#
# Copyright 2007 Michael L... |
################################################################################
# #
# PLOT ONE PRIMITIVE #
# ... |
import cv2
import tensorflow as tf
import matplotlib.pyplot as plt
CATEGORIES = ["Dog", "Cat"]
def prepare(filepath):
IMG_SIZE = 50
img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)
... |
def countzero(string):
output = string.count('()')
for x in string:
if x in 'abdegopq069DOPQR':
output += 1
elif x in '%&B8':
output += 2
return output
'''
Gigi is a clever monkey, living in the zoo, his teacher (animal keeper)
recently taught him some knowledge of... |
#!/usr/bin/python3
def delete_at(my_list=[], idx=0):
new_list = my_list.copy()
len_list = len(my_list)
if my_list:
if idx < 0 or idx >= len_list:
return my_list
else:
my_list.clear()
for i in range(len_list):
if i != idx:
... |
import dash_bootstrap_components as dbc
from dash import html
spinners = html.Div(
[
dbc.Spinner(color="primary"),
dbc.Spinner(color="secondary"),
dbc.Spinner(color="success"),
dbc.Spinner(color="warning"),
dbc.Spinner(color="danger"),
dbc.Spinner(color="info"),
... |
from sklearn import datasets
iris = datasets.load_iris()
x = iris.data
y = iris.target
from sklearn.naive_bayes import GaussianNB
clf = GaussianNB()
pre = clf.fit(x,y).predict(x)
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(pre, y)
print(accuracy) |
customers=['grandpa','grandma','cousin','sister']
print("I have found a bigger table to maintain more customers:")
customers.insert(0,"ant")
customers.insert(2,"prince")
customers.append("wife")
print("Hello "+customers[0]+", Welcome to my party!")
print("Hello "+customers[1]+", Welcome to my party!")
print("Hello "+cu... |
import torch.nn as nn
def get_criterion(version):
if version == 1:
criterion = nn.BCEWithLogitsLoss(reduction="mean")
else:
raise Exception(f"Criterion version '{version}' is unknown!")
return criterion |
import math
from collections import OrderedDict
from functools import partial
from typing import Any, Callable, Dict, List, Optional, Tuple
import torch
from torch import nn, Tensor
from ..ops.misc import Conv2dNormActivation, SqueezeExcitation
from ..transforms._presets import ImageClassification, InterpolationMode
... |
from rtmidi.midiutil import open_midiport
import schedule
import time, datetime, copy
from Midi import MidiEvent
class Sender:
"""
MIDIイベントの送信の機能をまとめたクラス
"""
def __init__(self):
"""
コンストラクタ
"""
self.midi_out, self.port = open_midiport(None, "output", client_name = 'sende... |
import numpy as np
import pandas as pd
from KNearestRegressor import KNearestRegressors
from sklearn.metrics import r2_score
from sklearn.metrics import accuracy_score
#taking inputs
data=pd.read_csv('Social_Network_Ads.csv')
X=data.iloc[:,2:4].values
y=data.iloc[:,-1].values
#using train_test_split function
from sk... |
'''
Created on 2015. 6. 20.
@author: 윤선
'''
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, title):
super(MyFrame, self).__init__(parent,\
title=title, size=(700,500))
# UI 초기화하는 메서드 호출
self.InitUi()
self.Center()
self.Show()
... |
from django.db import models
from django.urls import reverse
from visits.models import PerformanceBase
# Create your models here.
class Appointment(models.Model):
creation_date = models.DateField(auto_now_add=True)
appointment_date = models.DateField(verbose_name='date')
appointment_time = models.TimeFiel... |
from flask import Flask
app = Flask(__name__)
from knowledge_graph import routes, config |
# ----------------------------------------------------
# Name: Nicholas Houchois
# UNI: nbh2119
#
# Tester file for the effects.py module
# ----------------------------------------------------
import effects
def main():
print("Please choose the effect you would like to use: ")
print("1) object_filter")
... |
from django.urls import path, include
from .views import listaproductos, detalleproductos, MyPDF, some_view, DemoPDFView, render_pdf_view, agregarproveedor, \
agregarproveedor2, buscarproducto, ListarProveedor, ProveedorCreate
from venta.apis import urls as apiurls
app_name = "app1"
urlpatterns = [
path('lista... |
import os
from os import listdir
from order import Order
from drone import Drone
from warehouse import Warehouse
from math import sqrt,ceil
PATH = "../Google/"
class Main(object):
def __init__(self, filename):
super(Main, self).__init__()
self.filename = filename
self.orders=[]
self.warehouses=[]
self.drone... |
from controllers.property import PropertyController
from core.db import session
from flask_restful import Resource
from flask_restful import abort
from flask_restful import fields
from flask_restful import marshal_with
from flask_restful import reqparse
from models.property import Property as PropertyModel
from resourc... |
import configparser
import os
import logging
import multiprocessing
from datetime import datetime as dt
from apscheduler.schedulers.background import BlockingScheduler
PATH = r'\\app-solaroad01\data\Setup\Data'
DB_PATH = 'db'
DB_FILE = 'processedFiles.data'
LOG_PATH = 'log'
CONFIG_FILE = 'config.ini'
formatter = logg... |
#region Import Modules
from fluid_properties import *
import numpy as np
import pandas as pd
import math
from pyXSteam.XSteam import XSteam
import matplotlib.pyplot as plt
import pprint
#endregion
#region Inputs:
# Geometry
geometry={}
geometry['L']=0.69
geometry['W']=0.4
geometry['H']=2*(2/3)
# Ambient Conditions
... |
from CallBackOperator import CallBackOperator
from SignalGenerationPackage.Sinus.SinusUIParameters import SinusUIParameters
class SinusOmegaCallBackOperator(CallBackOperator):
def __init__(self, model):
super().__init__(model)
def ConnectCallBack(self, window):
self.window = window
s... |
from typing import Optional
from dataclasses import dataclass, field
from .base import StoreCfg, Schema
@dataclass
class NewsgroupStoreCfg(StoreCfg):
path: str = 'flex'
name: str = 'newsgroupbao'
local: bool = True
schema: Optional[Schema] = field(default_factory=lambda: Schema(
example_id=Non... |
""" File: shapes.py
Author: Abraham Aruguete
Purpose: So instead of doing something, I'm going to now implement some data structures. Please oh God be easy. """
def shape_alpha():
x = [ , ]
x[0] = [10, , ,40]
x[1] = [[1.1, -17], [123, 456]]
x[0][1] = "abc"
x[0][2] = "jkl"
def shape_br... |
lst = []
try:
while 1:
result = input()
if result.isupper() and result !=0:
L=result.split()
for i in L:
if i not in lst:
lst.append(i)
else:
continue
continue
else:
print(... |
import pandas as pd
from sklearn.naive_bayes import MultinomialNB
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import confusion_matrix
df = pd.read_csv('bbc.csv')
df.repertoire.value_counts()
'''
Encoder les categories de la variable cible
'''
le = LabelEncoder()
df['repertoire'] = le.fit_trans... |
import pygame,sys,random
pygame.init()
screen = pygame.display.set_mode([600,600])
screen.fill([255,255,255])
for i in range(50):
width = random.randint(0,250)
height = random.randint(0,250)
top = random.randint(0,250)
left = random.randint(0,250)
pygame.draw.rect(screen,[0,0,0],[left,top,width,heig... |
# Listcomps
symbols = '$¢£¥€¤'
codes = [ord(symbol) for symbol in symbols]
codesAsString = ", ".join(str(code) for code in codes)
print("The code points for the string '$¢£¥€¤' are", codesAsString)
# Tuples as records
traveler_ids = [('USA', '31195855'), ('BRA', 'CE342567'), ('ESP', 'XDA205856')]
for passport in sor... |
#coding:gb2312
#元组练习题
fruits=("apple","banana","peach","strawberry","orange\n\n")
print("Original items :")
for fruit in fruits:
print(fruit)
#fruits[0]=watermelon
#print(fruits) #修改元组元素是被禁止的
fruits=("litchi","banana","peach","pear","orange") #修改了其中两种水果
print("Modified items :")
for fruit in fruit... |
import numpy as np
from . IonSpeciesScalarQuantity import IonSpeciesScalarQuantity
from . OtherScalarQuantity import OtherScalarQuantity
class OtherIonSpeciesScalarQuantity(IonSpeciesScalarQuantity):
def __init__(self, name, data, description, grid, output, momentumgrid=None):
"""
Constru... |
from django.contrib import admin
from students.models import Student
admin.site.register(Student)
|
data = []
total_yeses = 0
with open("input.txt") as f:
# Use the same input from day 4
current_record = []
for line in f:
if line != "\n":
current_record = current_record + line.split(" ")
else:
current_record = [n.strip() for n in current_record]
data... |
import tkinter as tk
import app_main.main_ui as win
import app_main.make_widgets as mkw
import app_main.service as s1
import app_sub1.service_Student_Member as s2
import app_sub1.service_Video as s3
def main():
root = tk.Tk()
app = win.AppWindow(root)
root.geometry('%dx%d+%d+%d' % (400, 200, 10, 10))
s... |
import pymysql
# 项目运行的时候,加载pymysql模块
pymysql.install_as_MySQLdb() |
import pymysql.cursors
# 创建连接
config = {
'user':'root',
'password':'Bg1234',
'host':'192.168.15.211',
'port':3306,
'database':'bgdb'}
conn = pymysql.connect(**config)
# 创建游标
cur = conn.cursor()
# 执行查询SQL
sql = "select * from student"
cur.execute(sql)
# 获取查询结果
result... |
from tfcgp.problem import Problem
from tfcgp.config import Config
from tfcgp.evolver import Evolver
from tfcgp.learn_evo import LearnEvolver
from tfcgp.ga import GA
from sklearn import datasets
import numpy as np
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.FATAL)
c = Config()
c.update("cfg/test.yaml")
... |
i = [73,67,38,33]
for a in i:
if a >37 and a%5!=0:
p = a%5
q = (a-p)+5
print(q)
else:
print(a)
|
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import List
import pytest
from examples.finite_mtenv_bandit import FiniteMTBanditEnv # noqa: E402
from tests.utils.utils import validate_mtenv
def get_valid_n_tasks_and_arms() -> List[int]:
return [(1, 2), (10, 20), (100, 200)]
... |
import gzip, pickle
from tempfile import TemporaryFile
def convert(path):
"""
Builds a file containing a numpy array with a pkl file specified by path.
"""
with gzip.open(path, 'rb'):
data, label = pickle.load(f)
f_data = open("./data", 'w')
f_data
|
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
from torch.nn.functional import pairwise_distance, cosine_similarity
import argparse
import os
import sys
import numpy as np
... |
# To pass env vars to Python scripts run by Publik in services which remove custom env vars:
# https://unix.stackexchange.com/questions/44370/how-to-make-unix-service-see-environment-variables
# So we hardcode the values in the file below when the container starts
import sys
sys.path.insert(0, "/home")
from pyenv impor... |
import glob
import numpy as np
import argparse
import os
"""
Last modified on 04/22
related to v3.1
"""
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--samples', help='samples per small dataset file', type=int, default=300)
args = parser.parse_args()
single_sample_num = args.samples
bigdatafi... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 7 20:11:35 2018
@author: user
迴圈偶數連加
"""
a=int(input())
b=int(input())
i=a
sum=0
while i <= b:
if (i % 2 == 0):
sum=sum+i
i=i+1
print(sum) |
import tensorflow.keras as keras
model = keras.Sequential()
model.add(keras.layers.Dense(3))
model.add(keras.layers.Dense(5))
model.add(keras.layers.Dense(2))
model = keras.Sequential()
model.add(keras.layers.Dense(128))
model.add(keras.layers.Dense(100))
model.add(keras.layers.Dense(60))
model.add(keras.layers.Dense(... |
from __future__ import absolute_import, division, print_function, unicode_literals
from metaflow import FlowSpec,Parameter, step, batch, retry,catch,S3
import pandas as pd
import random
import numpy as np
import os
import torch
import tensorflow as tf
from transformers import BertTokenizer
from torch.utils.data import ... |
"""obc URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vie... |
"""
This file contains functions for (Quantized) Neural Networks
"""
__author__ = "Tibor Schneider"
__email__ = "sctibor@student.ethz.ch"
__version__ = "0.1.0"
__date__ = "2020/01/23"
__license__ = "Apache 2.0"
__copyright__ = """
Copyright (C) 2020 ETH Zurich. All rights reserved.
Author: Tibor Schneider, ET... |
from django.contrib import admin
from .models import Post, Comment, UserProfile, Notification, ThreadModel
admin.site.register(Post)
admin.site.register(Comment)
admin.site.register(UserProfile)
admin.site.register(Notification)
admin.site.register(ThreadModel)
|
import pgoapi
from pgoapi.utilities import f2i, get_cell_ids
from model.inventory import Inventory
class PgoWrapper(object):
def __init__(self, auth_type, username, password, messager):
self.logged_in = False
self.api = pgoapi.PGoApi()
self.last_result = None
self.inventory = None
... |
''' Does a simple linear regression plot
depends on statsmodels and pandas and patsy
See http://pandas.pydata.org/pandas-docs/stable/visualization.html for more details on pandas plotting
See http://statsmodels.sourceforge.net/stable/index.html for details on statsmodels
Regression http://pandas.pydata.org/pandas-docs... |
A = [1,3,4,5,7,6,4,5,10,1]
print(A)
# Boundary case
if A[0]>=A[1]:
print(A[0])
for i in range(0,len(A)-1):
if (A[i]>=A[i-1]) and (A[i]>=A[i+1]):
print(A[i])
# Boundary case
if A[len(A)-1]>=A[len(A)-2]:
print(A[len(A)-1])
|
from django.conf.urls import url
from django.urls import include
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework import permissions
schema_view = get_schema_view(
openapi.Info(
title="Car Management API",
default_version='v1',
description="Car hire mana... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-21 18:29
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... |
"""app_enquetes URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-... |
#this program is used to print the 2d array by using numpy
from data import functional
try:
row = int(input("enter the number of rows :"))
column = int(input("enter the number of columns :"))
functional.array(row, column) # calling the method and passing two values
except ValueError... |
import keras
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import cifar10
from IPython.display import clear_output
from keras import *
from keras.layers import *
# PLOTTER
class PlotLosses(keras.callbacks.Callback):
def on_train_begin(self, logs={}):
self.i = 0
self.x = []... |
import os
import h5py
import argparse
import numpy as np
from utils import vtk_plot
parser = argparse.ArgumentParser()
parser.add_argument("--model_id", type=str, default='07200224_3dunet')
opt = parser.parse_args()
print(opt)
data_dir = 'data/test'
input_files = [f for f in os.listdir('data/test') if f.endswith('_i... |
# Generated by Django 3.1.7 on 2021-04-01 03:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0004_auto_20210330_1844'),
]
operations = [
migrations.AlterField(
model_name='entry',
name='photo',
... |
def reverse_words(string):
return ' '.join(a[::-1] for a in string.split(' '))
|
# -*- coding: utf-8 -*-
# @Time : 2020/5/24
# @Author : J
# @File : 图像的基本操作.py
# @Software: PyCharm
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread("../image.jpg")
# px = img[100,100] #行和列坐标来访问像素值
# print(px)
#
# blue = img[100,100,0] #访问指定通道的像素值
# print(blue)... |
num1 = int(input("Enter num 1 : "))
num2 = int(input("Enter num 2 : "))
num3 = int(input("Enter num 3 : "))
print("Result of ",num1 ,"+" ,num2 ,"+" ,num3, "= ",num1+num2+num3)
print("2 X Num1 =",num1*2) |
from odoo_gateway import Session
from simple_timer import Timer
session = Session(['-c', '/Users/eneldoserrata/PycharmProjects/marcos_odoo/.openerp_serverrc', '-d', 'rim'])
cr = session.cr
lot_ids = [l.id for l in session.models.stock_production_lot.search([])]
count = 0
total_time = False
moves = set()
skua_ab = ... |
def getFriends():
friends = []
f = open("friends.txt", "r")
for line in f:
if line != "\n":
line = line.rstrip()
friends.append(line)
f.close()
return friends
def addFriend(name):
f = open("friends.txt", "a")
f.write(name + "\n")
f.close()
def deleteFrie... |
import matplotlib.pyplot as plt
speaker_results = open('F:\Projects\Active Projects\Project Intern_IITB\Desktop\\Vowel_opt_V3_MA.csv', 'r')
sr = speaker_results.read()
# print sr
list_data = sr.split('\n')
# print list_data
list_data.pop(0)
list_data.pop(-1)
list_data.pop(-1)
# print list_data
data = []
for j in list_... |
from helpers import assert_raises
# Recursion + Python
# =============================
# A recursive function has one or more base cases, inputs for which the
# function produces input trivially, and one or recursive cases, for which the
# program recurs.
# Like any other functional language, Python allows recursio... |
from django.shortcuts import render, redirect
from django.http import HttpResponse, Http404
from .models import Profile, Neighborhood, Follow, Business, Post
from .forms import ProfileForm, NeighborhoodForm, PostBusinessForm, PostMessageForm
from django.contrib.auth.decorators import login_required
from wsgiref.util... |
'''******************************************
ATHON
Programa de Introdução a Linguagem Python
Disiplina: Lógica de Programação
Professor: Francisco Tesifom Munhoz
Data: Primeiro Semestre 2021
*********************************************
Atividade: Lista 2 (Ex 3)
Autor: Yuri Pellini
Data: 19 de Maio de 2021
Comentários... |
# Generated by Django 2.2.4 on 2019-08-05 14:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Tag',
fields=[
('id', models.... |
"""
Copyright 1999 Illinois Institute of Technology
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publis... |
total_cost = 1 + 3 * 4
print(total_cost)
total_cost = 1 + (3 * 4)
print(total_cost)
print("BODMAS Rule") |
#!/usr/bin/env python3
# Copyright (c) 2021 Mahdi Biparva, mahdi.biparva@gmail.com
# miTorch: Medical Imaging with PyTorch
# Deep Learning Package for 3D medical imaging in PyTorch
# Implemented by Mahdi Biparva, April 2021
# Brain Imaging Lab, Sunnybrook Research Institute (SRI)
import sys
import torch
import n... |
#!/usr/bin/python
import os, sys, getopt, ConfigParser, logging, commands
def usage(supported):
print "\n"
print "glite-wn-info [-c <configfile>] [-h] [-v] -n <name>"
print "glite-wn-info [--config <configfile>] [--help] [--verbose] --name <name>"
print "\t-c <configfile>"
print "\t\tSpecify a conf... |
from __future__ import division
import numpy as np
import scipy.spatial as spatial
import sys
import time
import os
import pandas as pd
from joblib import Memory, Parallel, delayed
# from https://pypi.python.org/pypi/bintrees/2.0.2
from bintrees import FastAVLTree, FastBinaryTree
# from https://github.com/juhuntenburg/... |
"""
Sử dụng matplotlib.pyplot.plot vẽ các đồ thị hàm số f(x) = (e^(−x/10))*sin(πx) and g(x) = x*e^(−x/3) trong khoảng [0, 10] trên cùng một biểu đồ. Bao gồm trục x, trục y, và các chú thích các đường biểu diễn của từng hàm số. Lưu đồ thì thành một file plot.jpg (“Jpeg”)
"""
import os
import matplotlib.pyplot as plt
im... |
import sys
reload(sys)
sys.path.append('./plugins/')
sys.setdefaultencoding('utf-8')
import bayes
import controller
import os
import sae
import web
import jieba
web.config.debug = True
urls = (
'/', 'Index'
)
app_root = os.path.dirname(__file__)
templates_root = os.path.join(app_root, 'templates')
ren... |
import unittest
from katas.kyu_6.dashatize_it import dashatize
class DashatizeTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(dashatize(274), '2-7-4')
def test_equal_2(self):
self.assertEqual(dashatize(5311), '5-3-1-1')
def test_equal_3(self):
self.assertEq... |
def calcCost(weight):
return (weight // 3) - 2
def recursiveFuelCost(fuel):
extraFuel = calcCost(fuel)
return 0 if extraFuel <= 0 else extraFuel + recursiveFuelCost(extraFuel)
def CalculateFuelCost(moduleArr):
modulesTotal = 0
additionalFuelTotal = 0
for mass in moduleArr:
moduleFuel =... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import json
from OwhatLab.utils.mysqlUtil import MysqlClient
class OwhatLabPipeline(object):
def process_item(self, item... |
#!/usr/bin/python3
''' Establishing connection to database '''
from database_py.core import Getter
with Getter('test', 'test').credentials() as start:
start |
from rply import LexerGenerator
from globs import *
lg = LexerGenerator()
lg.add('FLOAT', '-?\d+\.\d+')
lg.add('INTEGER', '-?\d+')
lg.add('NULL', 'null(?!\w)')
lg.add('STRING', '(""".*?""")|(".*?")|(\'.*?\')')
lg.add('PRINT', 'print(?!\w)')
lg.add('BOOLEAN', f"{TRUE}(?!\w)|{FALSE}(?!\w)")
lg.add('IF', 'if(?!\w)')
lg.a... |
import os,sys
from scipy.ndimage import zoom
import json
from .io import readImage,mkdir
from .seg import rgbToSeg
import numpy as np
import shutil,json
from imageio import imwrite
def readTileVolume(fns, z0p, z1p, y0p, y1p, x0p, x1p, tile_sz, tile_type = np.uint8,\
tile_st = [0, 0], tile_ratio = 1, tile_... |
from sqlalchemy import Column, Integer, String, Float, ForeignKey, DateTime, Table, Boolean
from sqlalchemy.orm import relationship
from settings.database import Base
from utils.models import DateAware
# from sales.models import Sale
# Create your model here.
class User(DateAware):
__tablename__ = 'users'
u... |
apart = [[101, 102, 103, 104, 105], [201, 202, 203, 204], [301, 302, 303, 304], [401, 402, 403, 404], [501]]
#이차원리스트의 요소가 줄어들든 늘어나든 관계없이 모든 호실에 전단지를 부착해주세요
#이중for => range보다 그냥 for를 사용
floor = 1 #층수
for i in apart:
for j in i:
print("%d호 부착완료"%j)
print("%d층에 모두 부착완료\n"%floor)
floor += 1
|
from open_pension_crawler.OpenPensionCrawlSpiderBase import OpenPensionCrawlSpiderBase
class YlInvestSpider(OpenPensionCrawlSpiderBase):
name = 'yl-invest'
allowed_domains = ['yl-invest.co.il']
start_urls = ['http://www.yl-invest.co.il']
file_prefix = 'yl_'
regex = r'[0-9]{9}_(b|g|p|m)[0-9]{4}_(01... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.