text
stringlengths
8
6.05M
def addi(): a = int(input("Bitte die erste Zahl eingeben: ")) b = int(input("Bitte die zu addierende Zahl eingeben: ")) c = a + b print(c) def subbi(): a = int(input("Bitte die Zahl eingeben von der subtrahiert werden soll: ")) b = int(input("Bitte die Zahl eingeben die subtrahiert werden soll...
from django.contrib import admin # Register your models here. from django.contrib import admin from django.db import models from .models import TaggedPost from .models import PostTag from .models import Post admin.site.register(Post) admin.site.register(TaggedPost) admin.site.register(PostTag)
#Arkadaslar master odevimiz sudur ; #Bir dongu icerisinde random olacak sekilde iki tane 10x10’luk matris uretin ve bu matrislerin farklarini alin. #Ve fark matrisinin diagonali, -0.1 ile 0.1 arasinda olana kadar bu islemi tekrarlayin. #Istenilen matris bulundugunda program dursun ve toplam kac dongunun kuruld...
start = time.time()
""" # 今までの書き方 from dataclasses import * @dataclass class Card: suit: str rank: int def print_card(card): print(f"{card.suit}の{card.rank}") card = Card("heart", 10) print_card(card) """ """ # メソッドを用いた書き方 from dataclasses import * @dataclass class Card: suit: str rank: int def print_card(self...
from __future__ import absolute_import default_app_config = 'app.groups.apps.GroupsConfig'
# -*- coding: utf-8 -*- """ Created on Mon Feb 22 08:52:13 2021 @author: User """ import matplotlib.pyplot as plt # plt.style.use('ggplot') from glob import glob import os import numpy as np import pandas as pd os.chdir(r'C:\Users\User\Documents\08_publications\20210220_ijms\figure4') datadir = '../data/figure4/' ...
# This file is part of beets. # Copyright 2016, Adrian Sampson. # # 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, ...
#!/usr/bin/env python3 # # Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # Script to convert snapshot files to a C++ file which can be compiled and # link...
from blackjack import total from random import choice def dealer_strategy(hand, playerhand, turn, difficulty='normal'): if difficulty == 'easy': if turn == 1: if total(hand) < 7: return 'd' elif 7 <= total(hand) <= 11: return 'd' elif 12 <...
# -*- coding:utf-8 -*- from datetime import datetime from django.db import models # Create your models here. class City(models.Model): name = models.CharField(max_length=20, verbose_name=u"城市名称") desc_city = models.CharField(max_length=200, verbose_name=u"城市描述") add_time = models.DateTimeField(default=d...
class Solution: def cipher(self, input, key): result = "" new_key = key%26 for i in input: if i.isalpha(): if 65 <= ord(i) <= 90: if new_key+ord(i) > 90: decode = chr(ord(i)-(26-new_key)) ...
#Ikhventi race file import RaceBP, Buildables, Ships, Technology, Soldiers, Colonies class ikhventiRace(RaceBP.baseRace): def __init__(self): self.name = "The Ikhventi" self.traits = () def createStartingColonies(self): pass #List of ikhventi structures class ikhventi_Habitat(Buildables.baseStructure...
from collections import Counter with open('orc.txt', 'r') as myfile: data = myfile.read() sList = list(data) print(Counter(sList)) # then i found [t, y, i, a, l, e, q, u] is rare characters with occurrence = 1 but in the wrong order # so i found the each letter in the text file to determine the order that they appe...
from functions import isPrime def main(): num = 2 index = 1 while True: if isPrime(num): print(index, '-->',num) index+=1 if index==10002: break num+=1 if __name__ == '__main__': main()
import uvloop import asyncio import logging from colorlog import ColoredFormatter from tonga.models.structs.persistency_type import PersistencyType from tonga.stores.local_store import LocalStore, StoreKeyNotFound def setup_logger(): """Return a logger with a default ColoredFormatter.""" formatter = Colored...
# coding=utf-8 # @Author: wjn from config import choice_environment class MpApp(): # @property def mp_app(self): '''小程序打开接口''' domain = choice_environment.current_url api = '/mp-app' url = str(domain) + api return url
from test_data.login_credentials import LoginCredentials class Login(): """ Login Valid user """ # Step: Enter Username def enter_username(self, username): find_element("username_field_element").send_keys(username) # Enter Password def enter_password(self, password): find_e...
''' \ Usage: python b.py -n <file.fasta> -o <output.tsv> -c <coverage>''' import sys ... inputs = sys.argv if '-n' not in inputs and '-o' not in inputs: print (__doc__) else: f_in = inputs[inputs.index('-n') + 1] f_out = inputs[inputs.index('-o') + 1] cov = int(inputs[inputs.index("-c") + 1]) def gc_analy...
class Solution(object): def mergeKLists(self, lists): self.nodes = [] head = point = ListNode(0) for l in lists: while l: self.nodes.append(l.val) l = l.next for x in sorted(self.nodes): point.next = ListNode(x) poin...
import sys sys.path.append('../500_common') import lib import lib_ss if True: images = lib.get_images("data/result.html") else: soup = lib_ss.main("/Users/nakamurasatoru/git/d_genji/genji_curation/src/500_common/Chrome31", "Profile 3", 10) images = lib.get_images_by_soup(soup) collectionUrl = "https://utd...
mobile_number = input("Enter mobile number:") joined = '' split_array = list(mobile_number) for digit in split_array: print(digit) if digit == '1': joined +="ONE " elif digit == '2': joined += "TWO " elif digit == '3': joined += "THREE " elif digit == '4': joined += ...
import gc import glob import os import shutil import time import numpy as np import pandas as pd import tensorflow as tf from keras.callbacks import ModelCheckpoint from keras.models import load_model from sklearn.model_selection import KFold, StratifiedKFold, train_test_split from .utils import copytree class Kera...
from vpython import sphere, canvas, vector, color, material from math import sin, cos class Planet(object): def __init__(self, radius, s_pos, material = None, color = None): pass class Star(object): def __init__(self, radius, s_pos, color = vpython.colors.yellow): pass class Comet(object): def _...
import re script_1 = open("abc.txt", "r") lines = script_1.readlines() # print(lines[0]) # lab = int(lines[0],10) # print(lab) a = [] b = [] c = [] aflag = 0 bflag = 0 cflag = 0 for line in lines: if re.match('JavaScript', line): a = line.split() aflag = 1 if re.match('HTML', line): b = line.split() bfla...
""" Mixin with computed along horizon geological attributes. """ # pylint: disable=too-many-statements import numpy as np from cv2 import dilate from scipy.signal import hilbert, ricker from scipy.ndimage import convolve from scipy.ndimage.morphology import binary_fill_holes, binary_erosion, binary_dilation from skima...
from struct import Struct def write_records(records, format, f): record_struct = Struct(format) for r in records: f.write(record_struct.pack(*r)) def unpack_records(format, data): record_struct = Struct(format) return (record_struct.unpack_from(data, offset) for offset in range(0, len(data),...
from controllers.FakeController import FakeController from lib.Vehicle import Vehicle class FakeVehicle(Vehicle): def __init__(self): controller = FakeController() super().__init__(controller) if __name__ == '__main__': vehicle = FakeVehicle() vehicle.listen()
import unittest import coc_package class TestSubtractFunction(unittest.TestCase): def test_add_for_ints(self): self.assertEqual(coc_package.subtract(3, 5), 3 - 5) def test_add_error(self): with self.assertRaises(AttributeError): coc_package.subtract(3, "5") if __name__ == '__ma...
from django.db import models from django.db.models.deletion import CASCADE # Create your models here. class Location(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=300) def __str__(self): return self.address class Participant(models.Model): use...
import cx_Oracle as ora username = 'test' password = 'abcd1234' ip = '192.168.194.103' port = '1521' srvnm = 'orcl' tnsnm = ora.makedsn(ip, port, service_name=srvnm) conn = ora.connect(username, password, dsn=tnsnm) print('Connection Success!') curs = conn.cursor() # sqlid = input("请输入sqlid: ") sqlid = 'b7ghr8z9mm79...
import pygame import os from Card import Card from Player import Player class PlayerSprite(pygame.sprite.Sprite): def __init__(self, name, room, uniqueID, hand): super(PlayerSprite, self).__init__() self.ID = uniqueID self.name = name self.room = room self.surf = pygame.Surf...
# Task: Find the last ten digits of the number: 28433 * 2 ^ (7830457) + 1 # Take the last ten digits of the result of the expression # C * E^B + D def takeDigitFromExpression(C, E, B, D, numDigit): myMod = 10 ** numDigit return (((C % myMod) * pow(E, B, myMod)) % myMod + D % myMod) % myMod
from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$', views.game_index, name='game_index'), url(r'^(?P<id>[0-9]+)/$', views.game, name='game'), url(r'^(?P<id>[0-9]+)/(?P<res>.+)$', views.res, name='res'), ]
__author__ = 'brianmendoza' from Bio import Entrez, SeqIO import webbrowser import re import os class GenBankFile: def __init__(self, organism): Entrez.email = "bmendoz1@vols.utk.edu" self.directory = "/Users/brianmendoza/Desktop/GenBank_files/" self.org = organism def setOrg(self, ...
import urllib from BeautifulSoup import * url = raw_input('Enter - ') html = urllib.urlopen(url).read() soup = BeautifulSoup(html) #Retrieve all of the span tags tags = soup('span') num2= [] num3= [] for tag in tags: num1 = 'Contents:',tag.contents[0] for x in num1: num2 = int(num1[1]) num3.append(num2)...
from functools import reduce def f(x): return x*x r = map(f,[1,2,3,4,5,6,7,8,9]) print(list(r)) print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))) def fn(x,y): return x*10+y print(reduce(fn,[1,3,5,7,9])) def not_empty(s): return s and s.strip() print(list(filter(not_empty,['A',' ','',None,'B',' ','C']))) def _o...
# -*- extra stuff goes here -*- import permissions # make permissions available for GenericSetup permissions def initialize(context): """Initializer called when used as a Zope 2 product."""
# http://www.practicepython.org/exercise/2014/04/25/12-list-ends.html def principioFinal(lista): listares = [item for item in lista if (item == lista[0] or item == lista[len(lista)-1])] return listares a = [5, 10, 15, 20, 25] print(a) print (principioFinal(a))
import model from args import get_args from data import DataLoader from data import DcardDataset from data import customed_collate_fn import pickle from utils import load_training_args import torch def infer( total_test, test_id, test_x, sentence_length, my_model, ba...
#!/usr/bin/env python import sys import numpy as np import scipy.stats import logging import codecs from numpy import float64 from scipy.sparse import dok_matrix, csr_matrix, coo_matrix from sklearn.preprocessing import normalize logging.basicConfig( format="[ %(levelname)-10s %(module)-8s %(asctime)s %(relative...
myFloat = 2.0 # string (a string of characters) myString = "Bacon Pancakes" print (myFloat) print (myString)
# Exercício 5.15 - Livro total = 0 while True: preco = 0 invalido = False cod = int(input('Código do produto (0 para sair): ')) if cod == 0: print('=-=' * 10) break elif cod == 1: preco = 0.5 elif cod == 2: preco = 1 elif cod == 3: preco = 4 elif c...
from evidence_retrieval.data_source import DataSource from evidence_retrieval.data_source import ChineseTokenizer import os a = DataSource print(a.get_evidence('牙疼')) # .. print(os.pardir) # 当前文件夹路径 print(os.path.dirname(__file__)) # 上层路径 print(os.path.abspath(os.path.dirname(__file__)+os.path.sep+os.pardir)) # / prin...
# import psutil import os from os.path import join from time import time import pygame, sys, platform, psutil import pygame.display # Inicialização Pygame pygame.init() pygame.font.init() # Define e mostra a tela largura_tela = 1376 altura_tela = 800 tela = pygame.display.set_mode((largura_tel...
import os, subprocess, logging """ copied from network, """ def amr2mp3(amr_path, mp3_path=None): """ convert amr to mp3 just amr file to mp3 file """ path, name = os.path.split(amr_path) if name.split('.')[-1] != 'amr': print('not a amr file') return 0 if mp3_path is None or mp3_p...
#!usr/bin/env python3 # DECORATOR -- # def vermelho(retorno_funcao): # def modificaCor(retorno_funcao): # return f'\033[91m{retorno_funcao}\033[0m' # return modificaCor # # @vermelho # Decorator - Recebe o retorno da funcao abaixo e executa # def texto(texto): # return texto # #print(texto('Uma palavra...
def is_pal(n): return n == n[::-1] def is_skjult(n): return is_pal(str(int(n) + int(n[::-1]))) count = 0 for i in range(123454322): n = str(i) if is_pal(n): continue elif is_skjult(n): count += i print(count)
from argparse import ArgumentParser from microstrategy_api.microstrategy_com import MicroStrategyCom import logging log = logging.getLogger(__name__) def main(): parser = ArgumentParser(description="Reset a users password") parser.add_argument('server', type=str,) parser.add_argument('admin_user', type=...
# I, Michael Catania, agree to the Stevens Honor Code # This program determines whether a certain date is real def main(): date = input("Enter a date in month/day/year form:") m,d,y = date.split('/') mo = int(m) day = int(d) ye = int(y) if(mo==1 or mo==3 or mo==5 or mo==7 or mo==8 or mo==10 or m...
# 정수 N개로 이루어진 수열 A와 정수 X가 주어진다. # 이때, A에서 X보다 작은 수를 모두 출력하는 프로그램을 작성하시오. # N, X 입력 N,X = map(int, input().split()) # 수열 A를 이루는 정수 N개 입력 A = list(map(int, input().split())) for i in range(N): if A[i]<X: print(A[i], end=' ')
#!/usr/bin/env python import webapp2 import jinja2 import os from objects.usermeta import UserMeta from objects.player import * from objects.team import Team from utilities import * from google.appengine.api import users from google.appengine.ext import db jinja_environment = jinja2.Environment(loader=jinja2.FileSys...
n = int(input()) a = list(map(int, input().split())) a = [i + i%2 - 1 for i in a] print(*a)
from collections import defaultdict from pathlib import Path import numpy as np import pandas as pd from sklearn.metrics import accuracy_score import torch import torch.nn as nn from torch.utils.data import DataLoader from tqdm import tqdm from .. import nets from ..analysis.searchstims import compute_d_prime from .....
import sys import random t = None def triangle(): side_length = random.randint(5,50) for x in range(1,4): t.forward(side_length) t.left(360/3) t.up() t.forward(side_length+10) t.down() def circle(): radius = random.randint(5,18) t.circle(radius) t.up() t.forward(rad...
"""This takes a dictionary, adds values, changes them and displays those chages.""" Dict = {"name": "Chris", "city": "Seattle", "cake": "chocolate"} print Dict del Dict["cake"] print Dict Dict["fruit"] = "Mango" print Dict.keys() print Dict.values() print "cake" in Dict print "Mango" in Dict print "Mango" i...
import torch from torch.utils.data import Dataset import string translator = str.maketrans('', '', string.punctuation) import random import glob from PIL import Image import numpy as np from torch.nn.utils.rnn import pad_sequence import pickle DATA_DIR = '../../data/' FRAMES_DIR = '../../data/processed-frames/' ENVS_D...
import imported # only works if no __init__.py in this dir def test_doit(): assert imported.doit() == 999
from tkinter import * from tkinter import messagebox from tkinter import Menu from tkinter import * from tkinter import filedialog, Tk import os class ventana: def __init__(self, inter): self.interfaz = inter self.interfaz.geometry("1020x720") self.interfaz.title(" Bitxelart") self....
# -*- encoding:utf-8 -*- # __author__=='Gan' # Given a string S and a string T, # find the minimum window in S which will contain all the characters in T in complexity O(n). # For example, # S = "ADOBECODEBANC" # T = "ABC" # Minimum window is "BANC". # Note: # If there is no such window in S that covers all character...
import socket import struct import time import numpy as np import datetime from multiprocessing import Process from threading import Thread import cv2 import math from src.utils.templates.workerprocess import WorkerProcess from simple_pid import PID class LaneKeeping(WorkerProcess): pid = PID(Ki = 0.05, Kd = 0.0...
import vcr from sirepo_bluesky import SirepoBluesky @vcr.use_cassette('vcr_cassettes/test_smoke_sirepo.yml') def test_smoke_sirepo(): sim_id = '87XJ4oEb' sb = SirepoBluesky('http://10.10.10.10:8000') data, schema = sb.auth('srw', sim_id) assert 'beamline' in data['models'] @vcr.use_cassette('vcr_ca...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 21 10:15:26 2017 @author: Rafael Rocha """ import os import numpy as np # import my_utils as ut from glob import glob from skimage.transform import resize from skimage.io import imread from skimage.exposure import equalize_hist from skimage import ...
# Created by: David Wertenteil from Crypto.Cipher import AES import os # --------------- Functions ------------------------------------- def SIZE(): return 16 def div_16(o): r = [] for i in range(0, len(o), SIZE()): r.append(o[i:i + SIZE()]) return r def xor(o1, o2): return [ord(a) ^...
# -*- coding: utf-8 -*- from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.home), url(r'^user/login$', views.user_login), url(r'^user/create$', views.user_create), url(r'^user/logout$', views.user_logout), ]
# Endi shu while operatoridan foydalanim taxmin qilish oýinini yasaymiz # Biz bitta luboy sonni yashiramiz agar oýin ishtirokchisi 3 marta imkoniyat beriladi bu yashiringan nomerni topish uchun # Yashiringan sonni topsa yutadi agar 3 marta urunishda xam topolmasa yutqazadi guess_count=0# bu degani hisoblashni 0 dan bos...
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase, LiveServerTestCase from main.views import _split_message from main.models import Wall from django.cont...
from sqlcompletion import suggest_type def test_empty_string_suggests_keywords(): suggestion = suggest_type('', len('')) assert suggestion == (['keywords'], ['']) def test_select_suggests_cols_with_table_scope(): suggestion = suggest_type('SELECT FROM tabl', len('SELECT ')) assert suggestion == ('col...
import unittest from katas.kyu_7.counting_occurrence_of_digits import List class ListTestCase(unittest.TestCase): def setUp(self): self.lst = List() def test_equals(self): self.assertEqual(self.lst.count_spec_digits( [1, 1, 2, 3, 1, 2, 3, 4], [1, 3]), [(1, 3), (3, 2)]) def t...
import Addmodule as ad Key = input("Enter Developer name \t") ad.yashdictionary(Key)
#!/usr/bin/env python3 from autobahn.twisted.websocket import WebSocketServerProtocol, \ WebSocketServerFactory from twisted.python import log from twisted.internet import reactor import threading, sys, codecs, os, random, time, queue CODIGO = '-1::Salir'.encode('ASCII', 'ignore') LONGITUD = 207 conexiones = [] cla...
# -*- coding: utf-8 -*- """ @author: xiaoke @file: lengthOfLIS.py @time:2020-04-09 14:44 @file_desc: """ class Solution(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ l = len(nums) if l<=1: return l dp = [1] * l #...
# 提示说维护两个数组,后缀对应排除左移,前缀对应排除右移 # 两个合并考虑,应该能做 class Solution: def minimumTime(self, s: str) -> int: n = len(s) post, pre = [0] * (n+1), 0 # 维护后缀dp for i in range(n-1, -1, -1): if s[i] == "0": post[i] = post[i+1] else: post[i] = m...
import sys, os sys.path.append(os.pardir) import numpy as np from DeepConvNetwork import DeepConvNet from dataset.mnist import load_mnist (a_train, b_train), (a_test, b_test) = load_mnist(flatten=False) network = DeepConvNet() network.load_params("deep_convnet_params.pkl") sampled = 1000 a_test = a_test[:sampled] b...
# Copyright (C) 2020 FireEye, Inc. All Rights Reserved. import struct from .. import api class OleAut32(api.ApiHandler): name = 'oleaut32' apihook = api.ApiHandler.apihook impdata = api.ApiHandler.impdata def __init__(self, emu): super(OleAut32, self).__init__(emu) super(OleAut32,...
from .create import CreateTaskController from .load import LoadTaskController from .remove import RemoveTaskController
import pickle import os from tqdm import tqdm import sys import torch import numpy as np import random from torch.utils.data import TensorDataset import pymongo sys.path.append('/home/chenxichen/pycharm_remote/pycharm_py3.6torch/paper_one') def save_pkl_data(data, filename): data_pkl = pickle.dumps(data) with...
import os def renaming(): #variables savedPath = os.getcwd() print("Current Directory " + savedPath) # 1) get the file name and open it fileList = os.listdir("/Users/jamekaechols/Desktop/PythonShenanigans/HiringManagersOpenME") print(fileList) os.chdir("/Users/jamekaechols/Desktop/Python...
import heapq def topKFrequent(nums, k): obj = {} for i in nums: if i in obj: obj[i] += 1 else: obj[i] = 1 maxH = [] for key in obj: heapq.heappush(maxH, (obj[key], key)) if len(maxH) > k: heapq.heappop(maxH) res = [] while le...
#!/proj/sot/ska3/flight/bin/python ##################################################################################### # # # run_dea_perl_script.py: run DEA related perl scripts # # THIS M...
""" Fabric deployment script. """ from fabric import task def dotenv(git_ref): return f"APP_COMMIT={git_ref}" def archive(c): ref = c.local('git rev-parse --short HEAD', hide=True).stdout.strip() c.local(f"git archive -o {ref}.tar.gz HEAD") return ref def build(c): c.local('yarn build-prod') ...
import tensorflow as tf from lazy_property import lazy_property ''' using structure from https://danijar.com/structuring-your-tensorflow-models/ ''' class Model: def __init__(self, feature, label): self.feature = feature self.label = label self.prediction self.optimize self...
import unittest from Pyskell.Language.EnumList import L from Pyskell.Language.TypeClasses import * class HLTest(unittest.TestCase): def test_haskell_list(self): l1 = L[1, 2, ...] l2 = L[[1]] self.assertTrue(l1 > l2) self.assertFalse(l1 < l2) l3 = L[1, 3, ...] for ...
import sys filename = sys.argv[1] file = open(filename) numbers = {} fixes = {} for line in file.xreadlines(): parts = line.split("\t") length = len(parts) if length == 2: continue if length != 8 and length != 9 and length != 10: print length, line.replace("\t", "|") time = parts[0][1:]; lat = part...
import requests cdo_token = 'davQIOzciXPWdFXJzJLAZXGfCdyrOEiq' header = {'token': cdo_token} base_url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2' stations_endpoint = '/stations' params = {'limit': 1000, 'datasetid': 'lcd', 'startdate': '2019-12-01', 'enddate': '2019-12-31'} # response = requests.get(base...
n = int(input()) arr = list(map(int,input().strip().split()))[:n] stor = [] past = 0 for i in range(n): if past + arr[i] >= arr[i]: past = past + arr[i] else: past = arr[i] stor.append(past) ans = max(stor) print(ans)
#!/usr/bin/python def StrToInt(data): return ((ord(data[0]) << 24) + (ord(data[1]) << 16) + (ord(data[2]) << 8) + (ord(data[3]))) def IntToStr(num): result = '' for _ in range(4): char = chr(num & 255) result = char + result num >>= 8 return result def ReadByteArra...
#just try try again import os import numpy as np import random from PIL import Image import matplotlib.pyplot as plt import struct import time import logging logging.basicConfig(level = logging.INFO) #function: read images from MNIST which represent special numbers, from it to a matrix #input: filename->t...
n1 = int(input('type a random number')) d = n1 * 2 t = n1 * 3 r = n1 ** n1 print('You typed {} the double is {} the triple is {} and raiz is {}'.format(n1,d,t,r))
from PySide2.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QFileDialog, QPushButton from PySide2.QtGui import QPixmap from PySide2.QtCore import Qt from GPSPhoto import gpsphoto import webbrowser import os import sys import time class Window(QWidget): def __init__(self): super().__init__(...
# coding= UTF-8 # # Author: Fing # Date : 2017-12-03 # import numpy as np import scipy import sys sys.path.append('/home/suhas/Desktop/Sem2/audio-classification/data_try/libsvm-3.24/python/') from svmutil import * import sklearn from sklearn.model_selection import train_test_split # Load data from numpy file X_1 = ...
import sys, os, time from gevent_zeromq import zmq import monitor ctx = zmq.Context() sub_addr, router_addr = sys.argv[1:] sub_sock = ctx.socket(zmq.SUB) sub_sock.setsockopt(zmq.SUBSCRIBE, '') sub_sock.connect(sub_addr) req_sock = ctx.socket(zmq.REQ) req_sock.connect(router_addr) class Plugin(object): last_heartb...
import os import time import numpy as np import pandas as pd import scipy.io as sio from IPython.display import display import matplotlib.pyplot as plt import pywt import scipy.stats import datetime as dt from collections import defaultdict, Counter from sklearn.ensemble import GradientBoostingClassifi...
# Dijkstra's algorithm for shortest paths # Adapted from David Eppstein, UC Irvine, 4 April 2002 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117228 from priodict import priorityDictionary from Node2D import Node2DGraph def Dijkstra(graph,vertexCompare,start,end=None): """ Find shortest paths from the ...
# Copyright (c) 2016-2023 Knuth Project developers. # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. { "targets": [ { "target_name": "<(module_name)", 'product_dir': '<(module_path)', "sources": [ "src/kth-...
import os from tacotron.synthesizer import Synthesizer import tensorflow as tf def tacotron_synthesize(sentences): os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # ignore warnings https://stackoverflow.com/questions/47068709/ output_dir = 'A' checkpoint_path = tf.train.get_checkpoint_state('trained_model').model_checkp...
from collections import Counter def solution(k, tangerine): answer = 0 T = Counter(tangerine) for i in sorted(T.values(), reverse=True): if k > 0: k -= i answer += 1 return answer
from itertools import product import numpy as np import pandas as pd from ROOT import RooRealVar, RooCategory class ConfigurationError(Exception): pass class FitParameters(dict): class RealVar(): def __init__(self, *args): self.var = RooRealVar(args[0], args[0], *args[1:]) @pro...
# Generated by Django 2.2.6 on 2019-10-09 21:56 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('gtin', '0002_gtinbasedata'), ] operations = [ migrations.DeleteModel( name='GTINBaseData', ), ]
from django.contrib import admin from . models import * class PostAdmin(admin.ModelAdmin): search_fields = ('name', 'email', 'body') admin.site.register(Post, PostAdmin) admin.site.register(Category) admin.site.register(Tag) admin.site.register(Slider) admin.site.register(Studlife) admin.site.register(Ads) admin.s...