text
stringlengths
38
1.54M
import pyglet import random from Scene import Scene from Quad import Quad from GameObject import GameObject from VisibilityManager import VisibilityManager class GameScene(Scene): def __init__(self, objectManager, inputManager, space, width, height): Scene.__init__(self) self.objectManager = obje...
import torch import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt import numpy as np # Transforms images from [0,255] to [0,1] range. transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize(mean=[0], std=[1])]) # Load the set of training images. ...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^login/', views.user_login, name='login'), url(r'^signup/',views.user_signup,name='signup'), url(r'^level1/',views.level1,name='level1'), url(r'^level2/',views.level2,name='level2'), url(r'^level3',views.level3,name='level3'...
#!/usr/bin/python import os import re from pymill import Toolbox as tb class IterFile: _filename = '' _iteration = '' def __init__(self,filename): self._filename = os.path.abspath(filename) match = re.compile('.*?_iter_([0-9]+)').match(filename) if not match: match = r...
import requests import os from zipfile import ZipFile import ftp_file_loader # This module is used to download files from opendata.dwd.de def get_stations_metadata(file_loader, data_path): return file_loader.load_file("KL_Tageswerte_Beschreibung_Stationen.txt", data_path + "KL_Tageswerte_Beschreibung_Stationen....
import time start = time.time() triangle = [] for i in xrange(1,1000): triangle.append(i*(i+1)/2) f = open("/Users/shantanubal/Downloads/words.txt","r+") text = f.read() array = [] word = '' for each in text: if each == ',': array.append(word[1:-1]) word = '' else: word += each arr...
# -*- coding: utf-8 -*- import subprocess import re lines = subprocess.check_output(["ps","-x"]).splitlines() for line in lines: mo = re.match('\s*(\d+)\s*.*Dock.app/Contents/MacOS/Dock',line) if mo: subprocess.call(["kill",mo.group(1)])
from collections import defaultdict, OrderedDict from docopt import docopt import logging import time from scipy.sparse import dok_matrix from utils_ import Space from gensim.models.word2vec import PathLineSentences def main(): """ Make count-based vector space from corpus. """ # Get the arguments ...
import sys countArray=[0,0,0,0] tally=[[],[],[],[]] def symbolVal(symbol): if symbol=='A': return 0 if symbol=='C': return 1 if symbol=='G': return 2 if symbol=='T': return 3 def findFirstLast(k,top,bottom,symbol,s): #finding first occ: if s[top] == symbol and ...
from tools.util import Utility class Get_F_TestData: # 获取影片数据 @classmethod def get_f_film_query_excel_data(cls): f_query_info = Utility.get_json\ (Utility.get_root_path() + '\\conf\\Excel_conf\\C_FT.conf')[0] f_query_data = Utility.get_excel(f_query_info) return f_que...
""" Functions to select certain element indices from arrays. """ import numpy as np def multi_argmax(values: np.ndarray, n_instances: int = 1) -> np.ndarray: """ Selects the indices of the n_instances highest values. Args: values: Contains the values to be selected from. n_instances: Spe...
import numpy as np import matplotlib.pyplot as pl from prettytable import PrettyTable # Основная функция def func(x, y): return np.tan(y) + (np.abs(x) ** (1 / y)) # Диффиренциал по переменной x def df_x(x, y): return (np.abs(x) ** ((1 / y) - 1)) / y # Дифференциал по переменной y def df_y(x, y):...
from aoc import * def parse(l): return (l[0], int(l[1:])) def rotate(x,y): return (y,-x) s = sreadlines('input', parse) MOV, MOVDIR = [(1,0), (0,-1), (-1,0), (0,1)], 'ESWN' direct, loc = 0, (0,0) for act,v in s: if act in 'LR': direct = (direct+(v//90)*[-1,1][act == 'R']) % 4 elif act == 'F': loc = padd(loc, pm...
import allure from base.base_action import BaseAction import page class PageNewContacts(BaseAction): @allure.step(title="点击新建联系人") def click_new_contacts(self): self.base_click(page.new_contacts)
"""Tests for letsencrypt.client.achallenges.""" import os import pkg_resources import re import unittest import M2Crypto import mock from letsencrypt.acme import challenges from letsencrypt.client import le_util class DVSNITest(unittest.TestCase): """Tests for letsencrypt.client.achallenges.DVSNI.""" def s...
# Generated by Django 2.2.6 on 2019-11-11 01:02 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("home", "0005_countdown"), ] operations = [ migrations.RemoveField( model_name="countdown", name="stop_at_zero", ), ...
import pygame #import spritesheet #ss = spritesheet('hero_spritesheet.png') image = pygame.image.load('trump.png') class Enemy(pygame.sprite.Sprite): def __init__(self): super().__init__() width = 40 height = 60 self.sprites = [(34,111,60,71), (134,118,63,72), (234,115,61,73), (333,112...
# -*- coding: utf-8 -*- # copyrigth (c) 2015 Javier Campana <jcampana@cyg.ec> __author__ = 'Javier' class television(): def __init__(self, encendido=False, volumen=5, canal=0): self.encendido = encendido self.volumen = volumen self.canal = canal def prender(self): if self.enc...
#!/usr/bin/python2 import numpy as np lambd, size = 100, 100000 intervals = np.random.exponential(1.0/lambd, size) times = np.add.accumulate(intervals) bins = int(times[-1]-times[0]) print 'bins: ', bins rates = np.histogram(times, bins)[0] rates2 = np.random.poisson(lambd, bins) print 'rates: ', rates, 'rates2: ', r...
#!/usr/bin/env python # coding: utf-8 # ###### Steps to Making the Magic Happen: # # - Data preprocessing to get the hour and day of week for all entries in my training set. # - Used folium package to plot heatmaps of lat/long coordinates by time and day of week and saved these heatmaps in .html format # - Used selen...
from lxml import html import requests, os, shutil import pdb url = "http://www.presidency.ucsb.edu/debates.php" t = html.fromstring(requests.get(url).content) trs = t.xpath("//table/tr/td/table/tr") dems = [] reps = [] for tr in trs: tds = tr.getchildren() if len(tds) != 2: continue if not (tds[0]....
import logging import sys import time logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename='log\%s.log' % sys.argv[0], filemode='a') def input2int(func): ...
from app import app from models import db, Category, Subcategory, Admin, Trade, Issue, Issue_Parts, Part from flask_bcrypt import Bcrypt db.drop_all() db.create_all() category = Category(name="Plumbing") category1 = Category(name="Auto") category2 = Category(name="Appliances") category3 = Category(name="Ele...
#!/usr/bin/env python from __future__ import unicode_literals from __init__ import __version__ try: from setuptools.core import setup except ImportError: from distutils.core import setup setup( name='Dictsensors', version=__version__, description='Python Distribution Utilities', author='Jiri...
#!/usr/bin/python3 import common import sys if __name__ == '__main__': sys.exit(common.run(build_type="cc"))
import sys sys.path.append('.') import random import gym import torch from torch import nn from torch import optim from torch.nn import functional as F class DQNAgent: def __init__(self): """ Create an agent that uses DQN to guide its policy. This agent contains: - A hi...
# from django.contrib import admin # from tracker.models import Click # from .models import Bookmark # # # Register your models here. # class BookmarkAdmin(admin.ModelAdmin): # list_display = ('creator', 'url', 's_code') # # # class ClickAdmin(admin.ModelAdmin): # list_display = ('clicker', 'bookmark', 'timesta...
from django.contrib import admin #import models here from .models import Post from .models import Candle from .models import Stock from .models import StockDatabase from .models import Profile from .models import SimpleStock from .models import StockHandle from .models import moment from .models import IPO from .models...
import sys def read_file(textfile): f=open(textfile,'r') next(f) i=0 j=0 matrix=[[0 for x in range(9)] for y in range(9)] while True: j=0 char=f.readline() for c in char: matrix[i][j]=int(c) j=j+1 if j==9: i=i+1 break if i==9: break return matrix def check_soduku(row,column,number,m...
#!/usr/bin/python # Custom shite. from blog import say, Archive """ List the archive. Shows post titles and ids. Makes it so you don't have to guess indexes or whatever. """ say('Current posts:') arch = Archive() for index, post in enumerate(arch.items): say( ' {0} - {1}'.format( index, post['title'] ) ...
from .models import Subject def fetch_data_for_subjects_with_more_than_1_teacher(): context = [] subjects = Subject.objects.all() for subject in subjects: data = {} data['name'] = subject.name teacher_count = subject.teacher_set.count() if teacher_count > 1: ...
from django.db import models from django.utils import timezone from django.contrib.auth.models import User from datetime import datetime class Todo(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='todoes') body = models.TextField() created = models.DateTimeField(auto...
from .conf import * class TestMainLog: v_loss_list = [] a_loss_list = [] entropy_list = [] loss_list = [] envs_info = {} def __init__(self, ENV_CONF, log_root_path): self.ENV_CONF = ENV_CONF self._log_root_path = log_root_path self._log_path = os.path.join(self._log_ro...
#A library to operate the laser on our RPi import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) laser = 22 #the pin that the laser is connected to GPIO.setup(laser,GPIO.OUT) GPIO.output(laser,False) laser_on = False def isOn() : return laser_on def on() : global laser_on GPIO.output(laser,True) laser_on = True ...
def prime_checker(num): if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: print("It's not prime, it's divisible by ", i, " or ", i +2) ...
from django.db import models from student.models import Student # Create your models here. class ParentCommunicationCategories(models.Model): category = models.CharField(max_length=100) def __unicode__(self): return self.category class ParentCommunication(models.Model): student = models.Forei...
# coding: utf-8 import collections class Solution: def canVisitAllRooms(self, rooms): """ :type rooms: List[List[int]] :rtype: bool """ room_unlocked = set(list(range(1, len(rooms)))) queue = collections.deque() queue.extend(rooms[0]) while queue: ...
def import_trainer(name, model_parameters, parameters): # Trainer if name == 'standard_trainer': from LOP.Scripts.standard_learning.standard_trainer import Standard_trainer as Trainer kwargs_trainer = {'temporal_order': model_parameters["temporal_order"], 'debug': parameters["debug"]} elif n...
inputfile = open("Data/Grouped/Bangla/banglabhasa.txt","r",encoding="utf-8") inputword = inputfile.read() inputfile.close() arrstr = inputword.split("\n") keyword = set() for word in arrstr: if word not in keyword: keyword.add(word) preLine = '<news date= "Fri Jan 01 00:00:00 BDT 2010">\n' x = 1 y = 0...
""" General purpose utilities for PyBERT. Original author: David Banas <capn.freako@gmail.com> Original date: September 27, 2014 (Copied from pybert_cntrl.py.) Copyright (c) 2014 David Banas; all rights reserved World wide. """ import os.path import re from functools import reduce import pkgutil import importlib ...
from multiprocessing.managers import BaseManager import random import time import queue BaseManager.register('get_task_queue') BaseManager.register('get_result_queue') server_addr = '127.0.0.1' manager = BaseManager(address=(server_addr,5000),authkey=b'abc') manager.connect() task = manager.get_task_queue() result ...
from cart import views from django.contrib import admin from django.urls import path,include urlpatterns = [ path('', views.carts, name='cart_homepage'), path('<slug>/<pid>/', views.update_cart, name='update_cart'), path('data/', views.get_cart_data, name='data'), path('update/', views.change_qnt, name...
# -*- coding: utf-8 -*- """ Created on Thu May 17 17:08:20 2018 @author: zahra """ import re import numpy as np import matplotlib.image as image # read pattern sz = 10 #must be divisible by 5 img = image.imread('100x100_pattern_1.png') arr = np.array(img) data = np.array(arr[:,:,0]) pattern_digit = 5 yarnType = 'yarn...
# Copyright (c) 2019 The diadem authors # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. # ======================================================== from .base_summary import BaseSummary from .console_summary import ConsoleSummary from .pandas_sum...
#encoding=utf-8 import os import pickle from news import News newsTypes = ['人才培养','学校要闻','校友之苑','理论学习','媒体看工大','他山之石','时势关注','校园文化','科研在线','国际合作','服务管理','深度策划','综合新闻'] docId = 1 os.mkdir('Documents') for newsType in newsTypes: os.mkdir('Documents/%s' % newsType) #创建文件夹 with open('../DataCrawer/Data/%s.obj'...
from system.core.controller import * class Users(Controller): def __init__(self, action): super(Users, self).__init__(action) self.load_model('User') self.db = self._app.db def index(self): return self.load_view('index.html') def login(self): self.load_model('User'...
#!/usr/bin/python # a cli survey tool import sys import getopt import time import string from survey.survey import Survey from survey.question import Question survey_file='' response_file='' def getargs(argv): 'analyze command input' global survey_file global response_file try: opts, args ...
import numpy as np import pandas as pd import re import ggplot as gg import pylab as pl __all__ = ["Data", "plot", "get_scaling_factor"] """ Specific scaling code for the chemical dimerization data """ def get_scaling_factor(d, inhib_frame, stim_frame, n=10, return_max=True): """ To incorporate...
#!/usr/bin/env python ''' Filename: plot_tel_ADC_data.py Project: REASON Company: Jet Propulsion Laboratory ''' import matplotlib.pyplot as plt import os import sys #import math file_to_be_plot = sys.argv[-1] # 05-07-2018 This script will plot the voltage telemetry ADC values # ...
#Input stored in instructions as two letters, of which the first step represented by the first letter must be completed befroe the second can be undertaken instructions = [] raw = open("day7_input.txt","r") for line in raw: part1 = line[5] part2 = line[36] instructions.append([part1, part2]) raw.close() "...
import pylab, random import numpy as np import imageio import os, re def quick_sort(list_for_sort,start, end,k): x = range(len(list_for_sort)) i = start j = end-1 pivot = list_for_sort[start] while(i<=j): while(list_for_sort[i]<pivot and i<end): i +=1 while(list_for_sor...
from db import Submission, User, Task, Project from decorators import access_checks, user_checks from flask import request, abort from api import model from pony.flask import db_session from middleware.response_handler import ResponseHandler @db_session @access_checks.ensure_owner(Submission) def get_user_submissio...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Oct 15 22:01:25 2018 @author: varunmiranda Citations: https://www.geeksforgeeks.org/break-list-chunks-size-n-python/ https://stackoverflow.com/questions/17870612/printing-a-two-dimensional-array-in-python https://www.geeksforgeeks.org/minimax-alg...
alphalbet = 'QWERTYUIOPASDFGHJKLZXCVBNM' def Convert(string): list1=[] list1[:0]=string return list1 import random state = Convert(alphalbet) from PIL import Image, ImageDraw, ImageFont def strikethrough(text): return u'\u0336'.join(text) + u'\u0336' with open('words.txt','w') as f: for i in ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Feb 15 08:52:09 2019 @author: swec """ #import Tkinter, tkFileDialog # #win= Tkinter.Tk() # #win.title('Data augmentation with bounding boxes') #win.directory_destin= tkFileDialog.askdirectory(title=' name of the folder where the new images and data fi...
from time import time start = time() numbers = [] # generating lists of figurate numbers with 4 digits triangular = [n*(n+1)//2 for n in range(45, 141)] square = [pow(n, 2) for n in range(32, 100)] pentagonal = [n*(3*n-1)//2 for n in range(26, 82)] hexagonal = [n*(2*n-1) for n in range(23, 71)] heptagonal = [n*(5*n...
import math, sys, copy ao = 0.529177249 # following constants are adpoted from Burkhard's Physics.h eCharge = 1.602176462e-19 mu0 = 4.0*math.pi*1e-7 c = 299792458.0 eps0 = 1.0/(mu0*c*c) h = 6.62606876e-34 hBar = h/(2.0*math.pi) kb = 1.3806503e-23 fConst = eCharge*eCharge/...
#!/usr/bin/env python3 from .globals import * class Power: def __init__(self): self.chemical = 0 self.thermal = 0 self.electrical = 0 self.solar = 0 class Energy: def __init__(self): self.chemical = 0 self.thermal = 0 self.electrical = 0 self.so...
""" Supported column keys """ class Key: """Defines whether column is indexed and how""" def __init__(self, column_name: str, *args): """ :param column_name: Column affected by this key :param *args: A list of additional column names affected by key. Specify this to create a...
''' Created on Jul 15, 2013 @author: zero ''' from django.conf.urls import patterns, url from JSONService import views urlpatterns = patterns('', #/Mobile/ url(r'^$', views.index, name='index'), #/Mobile/GetCountries/ url(r'^G...
from django.contrib import admin from django.db.models import Count, Max from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin from django.contrib.auth.models import User from django.template.response import TemplateResponse from django.conf.urls import url from .models import Unit, Bazar, Category, Entry...
import random import numpy as np from numpy.testing import assert_array_equal import pytest from hypothesis import given from elsim.methods import star, matrix_from_scores import test_score score_ballots = test_score.score_ballots def collect_random_results(method, election): """ Run multiple elections with t...
# Rotina para reconhecer o poste em uma foto com rede treinada. import numpy as np from keras.models import load_model from cv2 import * import os import time # Ajustar o tamanho da imagem ao tamanho da entrada da rede from keras.preprocessing.image import img_to_array def podeOuNaoPode(x_, y_, shape_): if (x_ < sh...
######################################################################## # Author(s): Ashwin Kanhere # Date: 21 September 2021 # Desc: Constants required for calculations with GNSS measures ######################################################################## import numpy as np WE = 7.2921151467...
# -*- coding: utf-8 -*- """ Created on Wed Sep 2 14:07:11 2020 @author: TimChoi """ # for loops # for i in range(10): # 'range' creates an iterator -> in this case a series of values 0~9 # print(i) # for i in range(10): # print(i, end=' ') # end='' -> without new line # for i in range(1, 10): # set a start...
#kivy 1.9.1 from kivy.uix.screenmanager import Screen from kivy.properties import ObjectProperty from kivy.uix.gridlayout import GridLayout from kivy.metrics import sp from colorlabel import ColorLabel from dnd.treasure import Treasure, gemsValue, jewelryValue from dnd.loot import generateLoot class TreasureScreen(S...
#!/usr/bin/env python """ Encapsulates requests to Phedex API Should be usead instead of phedexSubscription. When used Directly, it creates a custodial subscription to a given site for a given list of datasets """ import json import urllib2,urllib, httplib, sys, re, os from xml.dom.minidom import getDO...
# Regression template # 1. Data Preprocessing # Import the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:,1:2].values # try to make X as matrix, y as vector y = dataset.iloc[:,2].values # =====...
import requests #program downloaded at beginning import Constants as Consts #We can refer to Constants as "Consts" now. class RiotAPI(object): #inherits objects, which is nothing #self is an instant of this ojbect _ = private __ = public def __init__(self, api_key, region = Consts.Regions['north_america']...
import nds2, subprocess, sys from gwpy.time import tconvert, from_gps, to_gps from pylab import * ion() def correct_time(): HOST = 'controls@10.0.1.156' COMMAND = 'caget -t -f10 C4:DAQ-DC0_GPS' ssh = subprocess.Popen(['ssh', '%s'% HOST, COMMAND], shell = False, ...
""" Samuel de Jesús Almejo Bautista Número de control: 18390583 Graficación 14/12/2020 Examen """ import matplotlib.pyplot as plt import numpy as np import math as mt plt.axis([0,120,0,120]) plt.axis('on') plt.grid(True) plt.title('Test 2D') plt.xlabel("Eje x") plt.ylabel("Eje y") #Radio r=15 #Centr...
# Copyright 2019 NOKIA # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
from PyQt5 import uic from PyQt5.QtWidgets import QMainWindow, QMessageBox, QVBoxLayout Ui_DataSetHist, UiBaseClass = uic.loadUiType('./view/datasethist.ui') from matplotlib.backends.backend_qt5agg import FigureCanvas, NavigationToolbar2QT from matplotlib.figure import Figure import pandas as pd import nump...
#!/usr/bin/env python3 import sys import unittest from itertools import islice sys.path.append("..") from pyS.S import math import primes_list factorization_result = { 0 : [], 1 : [], 2 : [1], 3 : [0, 1], 4 : [2], ...
#! /usr/bin/env python3 # H+ # Title : constants.py # Author : Matt Muszynski # Date : 09/11/17 # Synopsis: Master file for physical constants # # # $Date$ # $Source$ # @(#) $Revision$ # $Locker$ # # Revisions: # # H- # U+ # Usage # Example : # Output : # U- # D+ # # D- #####################################...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-12 15:54 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('places', '0003_country_and_attributes'), ] operations = [ migrations.AddField...
import unittest import os import sys from email.mime.text import MIMEText import time import pdb path = os.path.dirname(os.path.abspath(__file__)).split(os.sep) del path[-1] path = os.path.normpath(os.sep.join(path)) if path not in sys.path: sys.path += [path] from app.functions import * from app.task import Task ...
from common.common import make_tags # 포스트 내용 리스트 = 30개 list_content = ['워너원 강다니엘 멋있어' , '강다니엘 춤선 최고' , '강다니엘 콘서트 축하해' , '워너원 강다니엘 완전 섹시해' , '노래도 잘하는 울 강다니엘~~' , '강다니엘~ 워너블이 응원해요!!' , '아놔,, 강다니엘 넘 완벽한거 아님?' ...
from .YtMsg_pb2 import * import math class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __add__(self, o): return Point(self.x + o.x, self.y + o.y) def __sub__(self, o): return Point(self.x - o.x, self.y - o.y) def __truediv__(self, o): return Po...
import pytest import mappyfile from mappyfile_colors import ColorsTransformer, ConversionType from mappyfile.parser import Parser from mappyfile.transformer import MapfileToDict from mappyfile.pprint import PrettyPrinter def test_simple_api(): s = """ CLASS STYLE COLOR 184 13...
# coding=UTF-8 import torch import torchvision from chainercv.datasets.voc import voc_utils from torchvision import transforms from config import cfg from torch.utils.data import Dataset import numpy as np from net.ssd.net_tool import calc_target_ from tqdm import tqdm from .vocdataset import VOCBboxDataset from ....
import csv from statistics import variance from statistics import mean #convert string patterns to int patterns def read_pattern(line): p = [] for i in range(len(line)): if line[i] == ']': return p elif line[i] == '0' or line[i] == '1': p.append(int(line[i])) #given one...
import termios, sys, os import serial import time # set up serial port serialPortString = '/dev/ttyACM1' ser = serial.Serial(serialPortString, 9600) ser.open() ser.write(chr(0xa1)) ser.timeout = 0.1 speedValue = 75 movingForward = 1 def move(): ser.write(chr(0xff) + chr(0x00) + chr(speedValue)) ser.write(chr...
import pytest from subtract import subtract def test_subtract(): c = subtract(4, 5) assert(c == -1)
from argparse import ArgumentParser, Namespace from typing import TypeVar, Generic, NamedTuple, Optional, Sequence, Dict, Any from argtype.doc.google import OMIT_LINES _DESCRIPTION_KEY = "description" NamedTupleType = TypeVar("NamedTupleType", bound=NamedTuple, covariant=True) class TypedArgumentParser(ArgumentPars...
# -*- coding: utf-8 -*- """ Created on Tue Nov 08 23:14:26 2016 @author: cy111966 """ import sqlalchemy import toptrade as tp import sql import sys import logging import traceback if __name__=='__main__': """ python toptrade_entry.py 1 top_list 2016-11-08 """ try: fla...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys sys.path.insert(0,'../') import pandas as pd import numpy as np import datasplit.preprocessing as pp import datasplit.datasplit as ds import visualisation.data_visualisation as dv import random from sklearn import svm import scoring.fb_score as fb import dateti...
n=int(input("Enter Number: ")) for i in range(n): for j in range(3): print(i,end=' ') print()
import unittest import json import os from influxconnector.convertor.ppmp.v3.machine import PPMPMachine class TestPPMPMachine(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestPPMPMachine, self).__init__(*args, **kwargs) with open('./test/influxconnector/convertor/ppmp/v3/example...
# from main_calendar.models import Organization, User, Event # from rest_framework import serializers, viewsets # """ # Serializers allow us to define the shape and data types to be returned # in the api response. https://www.django-rest-framework.org/api-guide/serializers/ # """ # class UserSerializer(serializers.Hyp...
import torch.nn as nn import torch import math def rand_t(*sz): return torch.randn(sz) / math.sqrt(sz[0]) def rand_p(*sz): return nn.Parameter(rand_t(*sz))
def sum2(nums): t=len(nums) if t > 1: pri=nums[0] ult=nums[1] res=pri+ult elif t == 1 : pri=nums[0] res=pri else: res = 0 return res
## ## Originally created by https://www.reddit.com/user/AlekseyP ## Seen at: https://www.reddit.com/r/technology/comments/43fi39/i_set_up_my_raspberry_pi_to_automatically_tweet ## #!/usr/bin/python import os import sys import csv import datetime import time import twitter #Configuration # Twitter ACCESS_TOKEN="" ACCE...
def dicom_read(dicom_path): """ read dicom file to numpy and spacing list :param dicom_path:dicom path :return: data:numpy 3d; spacing: pixel spacing of numpy data """ def nii_read(nii_path): """ read nii file to numpy and spacing list :param nii_path: :return: """ def nii_wr...
from flask import Flask import dash import dash_bootstrap_components as dbc import json import networkx as nx server = Flask(__name__) # we pass this server to gunicorn for deployment app = dash.Dash(__name__, server=server, external_stylesheets=[dbc.themes.BOOTSTRAP])
# --------------------- # Imports from person import Person from product import Product from db import DataBase from classes import (Writer, Pen, Typewriter) # # --------------------- # # Instance Person class # person_one = Person('Ciclano', 25) # person_two = Person.by_birth_year('Fulano', 1996) # # ---------------...
help = "Uninstall packages and delete from dependencies" options = [ { "name": ["-g", "--global"], "dest": "global_", "action": "store_true", "help": "Remove packages from the global folder" }, { "name": "PACKAGE", "nargs": "+", "help": "Package name" ...
class Kiltalainen(): def __init__(self, name, type, kiltis): self.rp = 7 # kun rp laskee nollaan kiltalainen kuolee self.is_alive = True self.name = name self.type = type # joko tupsu tai fuksi 0 = fuksi, 1 = tupsu self.huone = kiltis def get_name(self):...
class Exception: def __init__(self): self.my_list = [] def input_numbers(self): while True: try: number = int(input('Введите числа в список, по окончанию нажмите "stop"')) new_list = self.my_list.append(number) except: pri...
# @Time : 2018/11/1 22:43 # @Author : Yanlin Wang # @Email : wangyl_a@163.com # @File : 1. 10minutes_to_pandas.py from time import clock import pandas as pd import numpy as np import matplotlib.pyplot as plt # series s = pd.Series([1, 3, 5, np.nan, 6, 8]) # print(s, s.dtype, type(s)) # 生成时间序列 dates = pd.da...