text
stringlengths
38
1.54M
class ClientSocket: def __init__(self, socket): self.socket = socket def send(self, message): pass def receive(self): pass def prompt(self, prompt_message): self.socket.sendall(prompt_message.encode('utf-8')) return self.socket.recv(1024).decode('utf-8')
# -*- coding: utf-8 -*- """ Utilities related to optimisation. """ import logging from typing import Optional import numpy as np from scipy.optimize import minimize from scipy.special import logsumexp logger = logging.getLogger(__name__) def optimise_meta_proposal_weights( samples: np.ndarray, log_q: np.nd...
from api.PersonalCenter.PersonalCenter import * class Pam(): def __init__(self,api_url, **kwargs): self.api_url = api_url self.personnal = PersonalCenter(self.api_url,**kwargs)
from BanahawApp import Session,Mini_func from BanahawApp.table import T_Facial_Services class Facialmodel(Mini_func): def __init__(self, **kwargs): self.__session = Session() self.__args = kwargs def get_services(self): retval = None result = self.__session.query(T_Facial_Services).all() te...
import json import dateutil.parser from typing import Dict class ReferenceError(Exception): pass class References(object): def __init__(self, references: Dict[int, 'Reference']) -> None: self.references = references def to_json(self): return {key: value.to_json() for key, value in self....
from utils import * class Config(object): def __init__(self): self.model_name = 'bert' self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') self.num_classes = 2 self.bert_path = './Model' self.hidden_size = 768 self.tokenizer = BertTokenizer...
import os import pdb import numpy as np import pandas as pd from numpy import savetxt from sklearn.model_selection import train_test_split from load_data import LoadData # USE MAP DICT TO READ INPUT FROM DEEPLEARNING # drug -[drug_map]-> drug_name(drug_i, drug_j) # celllinename -[celllinemap]-> cellline_name # ...
""" Created By : Nikesh Created On : Reviewed By : Reviewed On : Version : """ import datetime from PIL import Image from fuzzywuzzy import fuzz class Validation: def __init__(self, is_valid=True, validation_message="Not a valid Object", validation_object=None): self.is_valid = is_valid self.val...
import logging from os import path import itertools from typing import Any, Dict, List, Optional import torch from torch.nn import functional as F from overrides import overrides from allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.modules import FeedForward, Seq2SeqEncoder from ...
import requests from bs4 import BeautifulSoup from lxml import html from requests.compat import quote_plus def ins(name): features=[] headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'} instructables='https://www.inst...
# -*- coding: utf-8 -*- # # Original code from https://github.com/manelromero/checkpoint # A library for communicating with Check Point's management server using # written by: Check Point software technologies inc. # tested with Check Point R80 (tested with take hero2 198) # # Code updated to python 3.X compatibility #...
class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ if path is "": return path path_elems = path.split("/") new_path_elems = [] i = 0 while i<len(path_elems): if path_elems[i] =...
from nose.plugins.attrib import attr from pages.ATG_login_page import ATGLoginPage from utility.drivermanager import DriverManager import logging from utility.services import Services from pages.post_detail_page import PostDetailPage #task 10 @attr(website=['party', 'world']) class PostDetailShareTest(DriverManager): ...
#!/usr/bin/env python # _*_ coding:utf-8 _*_ ''' @author: yerik @contact: xiangzz159@qq.com @time: 2018/6/26 9:38 @desc: poloniex 数据抓取 ''' import json import numpy as np import os import pandas as pd import urllib import time ts = { '2015': 1420041600, '2016': 1451577600, '2017': 1483200000, '20...
import requests import pandas as pd from bs4 import BeautifulSoup from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument('--incognito') driver = webdriver.Chrome(executable_path = '/Users/drarn/Documents/Code/Study/BigData/WebScraping/chromedriver', options = options) url = 'https://w...
#!/usr/bin/python # -*- coding: utf-8 -*- # Create your views here. from django.db import models from django import forms from django.forms import ModelForm from django.db.models import Q from django.core.context_processors import csrf from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts i...
from django import forms from django.contrib import admin from django.urls import reverse from django.db.models import Count from django.utils.html import format_html from adminsortable2.admin import SortableInlineAdminMixin, SortableAdminBase from core.forms import RichTextField from eligibility.models import Eligib...
#coding=utf-8 import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import torch.nn.functional as F from word2vec import SkipGramModel import dataset def get_input_layer(word_idx): x = torch.zeros(vocabulary_size).float() x[word_idx] = 1.0 return x def main():...
#homeview.py from django.shortcuts import render from models import Bulletin, UserData from django.http import HttpResponseRedirect from ajaxviews import pullfeed import datetime def home(request): me = UserData.objects.get(pk=request.session['pk']) helps = pullfeed(UserData.objects.get(pk=request.session['pk'...
class Solution: def nthUglyNumber(self, n: int) -> int: ugly = [1] if n<1: return ugly[0] two = 2 three = 3 five = 5 index2 = 0 index3 = 0 index5 = 0 count = 0 while count<=n: count+=1 minimun ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2009 Timothée Lecomte # This file is part of Friture. # # Friture is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as published by # the Free Software Foundation. # # Friture is distri...
import requests from time import sleep url = input('url: ') timeout = int(input('timeout: ')) try: resp_url = requests.get(url,timeout=timeout).url except: print('Could not connect to the site') quit() def request(url,timeout): try: resp = requests.get(url,timeout=timeout) except: ...
import numpy as np from os.path import isfile import random total_iter = 100 min = 0.06 max = 1.5 bars = 18 class partical: def __init__(self, A=np.zeros((1, bars))): self.fits = 0 self.A = A self.density = 0.1 self.pbest = None self.pbest_fit = Non...
from django.db import models from django.utils.translation import ugettext_lazy as _ from users.models import Profile from .validators import phone_regex from .custom_fields import ListField from PIL import Image # WEEKDAYS = [ # (1, _("Monday")), # (2, _("Tuesday")), # (3, _("Wednesday")), # (4, _("Th...
class Atm(object): def __init__(self,card_number,pin): self.card_number = card_number self.pin = pin def wth(self): print("Money withdrawn...") def statement(self): print("Account statement:-") prin...
# Квадратная матрица поменять минимальный элемент и дигональный элемент строки. def getMatrix(): size = int(input('Введите размер квадрвтной матрицы: ')) matrix = [0] * size print('Построчно введите элементы матрицы:') for i in range(size): matrix[i] = list(map(float, input('> ').split()...
data = open("./Day8/day08.input").read().splitlines() ops = {"+": lambda x: x, "-": lambda x: -x} def execute_game(data, score, step, steps_completed): operation, argument = data[step].split(" ") if step in steps_completed: return score steps_completed.append(step) if operation == "nop": ...
# coding=utf-8 import os from pytoolbox.util import pmc_config from pytoolbox.util.pmc_config import read_string class App: ADMINS = ['liufan@lvye.com', 'yiwang@lvye.com', 'mengyu@lvye.com', 'zhoushiwei@lvye.com'] JSON_AS_ASCII = False SECRET_KEY = os.environ.get('SECRET_KEY') or '.yek eyvl' TESTING =...
# ANI2102A19/sitecustomize.py | Programmation Python avec Maya | coding=utf-8 # Exemple d'un script de configuration lancé à l'initialisation de l'interpréteur Python, avant le démarrage de Maya. # Pour être exécuté, le fichier doit absolument s'appeler 'sitecustomize.py' et se trouver au bon emplacement : # Windows:...
from pprint import pprint # читаем адресную книгу в формате CSV в список contacts_list import csv import re def opening_file(): with open("phonebook_raw.csv", encoding='utf-8') as f: rows = csv.reader(f, delimiter=",") contacts_list = list(rows) # pprint(contacts_list) return contacts_list ...
import multiprocessing import random import time def f(q): while True: rn = random.randint(1, 100) q.put([rn, None, 'hello']) time.sleep(0.2) def g(q): while True: rn = random.randint(1, 100) q.put([rn, None, 'goodbye']) time.sleep(1.2) if __name__ == '__main__...
# -*- coding: utf-8 -*- from tree import xmlTree from Node import node import time import sys from GUI import * from computeTree import * #create a tree from scratch def test1(): tree = node() root = tree #first child newChild = root.addNode("par")#parallel #notice that the childlist start fr...
""" Adapted from: Modification by: Gurkirt Singh Modification started: 2nd April 2019 large parts of this files are from many github repos mainly adopted from https://github.com/gurkirt/realtime-action-detection Please don't remove above credits and give star to these repos Licen...
from celery import Celery app = Celery('celery_back', broker='redis://:package_thief@localhost:6379', task_serializer='pickle', result_serializer='pickle', include=['celery_back.tasks']) app.conf.task_serializer = 'pickle' app.conf.result_serializer = 'pickle' if __name__=='__main__': app...
import numpy as np from time import clock from sklearn import svm from dataloader import get_dataset from argparse import ArgumentParser from multi_kernels import MultiKernelheuristic as mkh from multi_kernels import MultiKernelfixedrules as mkfr from sklearn.model_selection import StratifiedKFold parser = ArgumentPar...
import re from functools import partial from common import file_to_lines class ValidatorsFactory: def create_min_max_validator(self, min, max): return partial(self._check_minmax, min, max) def create_min_max_map_validator(self, map): return partial(self._check_minmax_map, map) def creat...
def ascci3(n): i=0 for k in range(n): print "%"*n i+=1 #output: >>> ascci3(6) %%%%%% %%%%%% %%%%%% %%%%%% %%%%%% %%%%%% >>> def createdonerow(width, height): A='' row='' for row in range(height): row='' for col in range(width): row+='*' A+='*' ...
from modules.color import Color from modules.vector import Vector from modules.image import read_ppm class Texture: def __init__(self, texture_file, u_vector=Vector(0,0.1,0), v_vector=Vector(0,0,0)): self.map = read_ppm(texture_file) self.width = self.map.width self.height = self....
import socket import threading import urlparse import select BUF_LEN = 8192 BUFLEN=8192 class MyProxy1(threading.Thread): def __init__(self,conn,addr): threading.Thread.__init__(self) self.source = conn self.request = "" self.headers = {} self.destnation = socket.socket(so...
import numba from numpy import * from plucked_map import * @numba.jit(nopython=True) def accumulate(nbins, n, m, s): density = zeros(nbins) dx = 2.0/nbins x = 2*rand() for i in range(n): x = osc_tent(x, s, m) bno = int(x//dx) density[bno] += 1/n/dx return density @numba.jit(...
#!/usr/bin/env python # -*- coding: utf-8 -*- def product_of_array_except_self(nums): length = len(nums) l = [1] * length r = [1] * length res = [1] * length for i in range(1, length): l[i] = l[i-1] * nums[i-1] for i in reversed(range(length-1)): r[i] = r[i+1] * nums[i+1] ...
import Data_Utils1 from sklearn.model_selection import StratifiedKFold from sklearn.preprocessing import StandardScaler, normalize from sklearn import svm from sklearn.neural_network import MLPClassifier from sklearn.feature_extraction.text import TfidfTransformer from sklearn.model_selection import StratifiedKFold fro...
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: def findRightInterval(self, intervals): lookup = [] for idx, val in enumerate(intervals): lookup.append((val.start, idx)) lookup.so...
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'AuthKey' db.create_table('urlauth_authkey', ( ('id', self.gf('django.db.models...
#!/usr/bin/env python import ADC0832 import time import math def init(): ADC0832.setup() def loop(): while True: analogVal = ADC0832.getResult() Vr = 5 * float(analogVal) / 255 Rt = 10000 * Vr / (5 - Vr) temp = 1/(((math.log(Rt / 10000)) / 3950) + (1 / (273.15+25))) temp = temp - 273.15 print 'temperatu...
#!/usr/bin/env python # -*- coding: utf-8 -*- # HOST = "192.168.10.120" PORT = 4223 GPSUID = "cPA" SERVOUID = "9oVKfGxvXL7" motor = 5 steeringsrv = 1 stop = 400 mid = 0 speed = 3000 earthRadius = 6371140 #in meters point1 = 48.799332, 9.051900
import sys import collections x = [1, 0, -1, 0] y = [0, 1, 0, -1] while True: W, H = map(int, sys.stdin.readline().split()) if W == 0: break tile = [[0 for i in xrange(W + 2)] for j in xrange(H + 2)] visited = set() next = set() for i in xrange(H): line = raw_inpu...
import pytest from .pages.basket_page import BasketPage from .pages.login_page import LoginPage from .pages.main_page import MainPage from .pages.product_page import ProductPage from .pages.search_page import SearchPage link = "http://selenium1py.pythonanywhere.com/" class TestSearchFromMainPage(): def test_gu...
from selenium import webdriver import requests url = 'http://www.shanyaoo.com/_account/login.shtml' driver = webdriver.Chrome() #登录时没有验证码的情况下可以不打开浏览器,selenium # option_chrome = webdriver.ChromeOptions() # option_chrome.add_argument('--headless') # driver = webdriver.Chrome(chrome_options=option_chrome) driver.get(url...
# -*- coding: utf-8 -*- """ Created on Fri Dec 4 01:13:25 2020 @author: ASUS """ import shapefile # mengimport library shapefile w=shapefile.Writer("soal8", shapeType=shapefile.POLYGON) # inisialiasi untuk Membuat file shapefile baru menggunakan Writer dan membuat oject baru w.shapeType # menentukan shapeType nya w...
############################################################################## # # Copyright (c) 2002, 2018 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # TH...
# # Copyright (c) 2020 Cord Technologies Limited # # 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 ag...
from stellar_sdk import operation def add_payment_op(source_account, destination_account, asset, amount): op = operation.payment(destination_account, asset, amount, source_account) return op
import itertools as it import numpy as np from sklearn.linear_model import LogisticRegressionCV from sklearn.pipeline import make_pipeline from sklearn.preprocessing import FunctionTransformer def make_clf(*args, **kwargs): clf = make_pipeline(FunctionTransformer(crossterm), LogisticRegre...
"""Handles reading the dictionary of ItemTypes from the XML file. This is largely copied from the original author's repository, just a bit stripped down. In particular, this stripped down version requires the XML file to be topologically sorted. https://github.com/Omnifarious/factorio_calc/blob/master/factorio_calc.p...
""" Generate regions """ import csv import os from .base import BaseGen class Regions(BaseGen): def __init__(self, config): super().__init__(config) def run(self): """Generate regions jsons""" csv_path = os.path.join(self.config.csv.base, self.config.csv.path.regions) region...
# Filename: ps2_controller.py # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAM...
# regular printing print("Hello, world") # printing with a different line-end character print("Hello, ", end='') print("world")
#1 import try: import configparser except: from six.moves import configparser import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import requests #2 variable related to weather API weather_dict = {'freezing_rain_heavy': 'Heavy rain and snow', 'freezing_rain': 'Ra...
spożywka = ["chleb", "mleko", "ser", "szynka", "masło"] print(spożywka) print(spożywka[0]) print(spożywka[4]) print(spożywka[-1]) print(spożywka[::4]) print(spożywka[0]) print(spożywka[4]) print(spożywka[0] + " " + spożywka[4]) print(spożywka[0], spożywka[4])
#coding=utf-8 from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains # br=webdriver.Chrome() # br.get("https://www.baidu.com") # br.maximize_window() # element=br.find_element_by_link_text("新闻") #单击元素 # ActionChains(br).click(element).perform() #元素上按下左键不放 # element=b...
from threading import Thread import serial, time class Drill(Thread): def __init__(self, port, get_next_block, block_done, emit_state): Thread.__init__(self) self.port = port self.current_block = None self.get_next_block = get_next_block self.block_done = block_done ...
#%% import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates from numpy.polynomial import Polynomial as P from numpy.polynomial import Chebyshev as T from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures import seaborn as sns from sk...
cart={ '天谕':{'近战':["光刃","圣堂","业刹"], '远程':["炎天","玉虚","灵珑","流光"]}, '阴阳师':{'SSR':["一目连","荒","茨木童子"], 'SR':["姑获鸟","妖狐","夜叉"], 'R':["椒图","山兔","雨女"]}, '王者荣耀':{'法师':["诸葛亮","貂蝉","妲己"], '刺客':["兰陵王","荆轲","李白"], '射手':["李元芳","马可波罗","百里守约"]} } count...
print "hi" print "helo" <<<<<<< HEAD #this is a brach # master commit # test changes #git hub edit
from selenium import webdriver class Driver_Factory(): def __init__(self, browser='ff', browser_version=None, os_name=None): self.browser = browser def get_web_driver(self, browser): web_driver = self.run_local(browser) return web_driver def run_local(self, browser): loc...
#!/usr/bin/env python import json infname = 'toolshed_data.json' data = json.load(open(infname, 'r')) cats = json.load(open('categories.json', 'r')) catdict = {} for cat in cats: catdict[cat['id']] = cat['name'] tools = {} for entry in data: if entry['type'] == 'unrestricted': cats = entry['category_ids'] for c...
# Problem: Given scores of N althletes # Return their relative ranks and the people with the top 3 scores class Solution(object): def findRelativeRanks(self, nums): """ :type nums: List[int] :rtype: List[str] """ ranks = {} numsSorted = sorted(nums) numsSorte...
from heapq import heapify, heappop, heappush N, *a = map(int, open(0).read().split()) q = a[:N] heapify(q) b = [0] * (N + 1) b[0] = sum(q) for i in range(N): x = q[0] y = max(heappop(q), a[N + i]) heappush(q, y) b[i + 1] = b[i] - x + y q = [-x for x in a[2 * N:]] heapify(q) c = [0] * (N + 1) c[N] = -...
import requests import time import json from datetime import date, datetime import re accessToken = '' api_url = 'https://api.vk.com/method/' NUM_OF_USERS = 50 app_params = { 'access_token' : accessToken, 'v' : '5.131' } def process_raw_str(string): return re.sub(r'[\W]', ' ', string).lower() ''' Сначала...
name = input('What is your name? ') print('Hi ' + name) main_name = input('What is your name? ') print('Hi ' + main_name) color = input('What is your favourite colour? ') print('Hi ' + main_name + ' you like colour ' + color)
nums=[12,13,14,15,10,18] for num in nums: if num %5==0: print(num) break else: print("not found")
#! /use/bin/python class Solution: def binarySearch(self, A,target): start, end = 0, len(A) while start+1 < end: mid = (start+end)/2 if A[mid] > target: end = mid elif A[mid] == target: start = mid else: ...
import pickle import time import numpy as np import tensorflow as tf from collections import Counter from sklearn.utils import shuffle from imblearn.under_sampling import RandomUnderSampler from tensorflow.contrib.layers import flatten with open('data_us.pickle', mode = 'rb') as f: dataset = pickle.load(f) x_t...
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'ui_main.ui' ## ## Created by: Qt User Interface Compiler version 6.1.0 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ###################...
# -*- coding: utf-8 -*- ''' :Author: stransky ''' import morphjongleur.util.auto_string import numpy class Compartment(object): ''' classdocs @see http://web.mit.edu/neuron_v7.1/doc/help/neuron/neuron/classes/python.html#Section ''' def __init__(self, compartment_id, compartment_parent_id, radius=1...
import re from lxml import etree import time class Post(object): def __init__(self,uid,s): self.s=s self.uid=uid # 选取某个小组进行发帖 def posting(self,group,uid,s): pass # 获取已经发的帖子 def readyPosts(self,uid,s): pass # 顶贴 def topPost(self): pass
#!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that pers...
import math import hashlib # Function to left # rotate n by d bits def leftRotate(n, d): INT_BITS = 8 return (n << d) & 0xFF | (n >> (INT_BITS - d)) # Function to right # rotate n by d bits def rightRotate(n, d): INT_BITS = 8 return (n >> d) | (n << (INT_BITS - d)) & 0xFF def ByteIn...
# Algorithm for non-continuous blobbing from lucidreader import LucidFile import numpy as np import math class BlobFinder: def square(self, x, y, size): half_size = (size - 1) / 2 x, y = x - half_size, y - half_size # Return a sizexsize square of pixels around the coordinates pixels = [] for i in range(s...
import numpy as np import matplotlib.pyplot as plt def get_solidblockage(aircraft,tunnel,bool): t1w = 0.87 k1w = 1.02 esb_w = (k1w * t1w * aircraft.wing.V) / ((tunnel.C) ** (3 / 2.)) t1f = 0.86 k3f = 0.915 esb_f = (k3f * t1f * aircraft.fuselage.V) / ((tunnel.C) ** (3 / 2.)) t1ss = 0.86 ...
import cv2 import numpy as np import matplotlib.pyplot as plt #from matplotlib import pyplot as plt from tkinter import filedialog from tkinter import * root = Tk() root.withdraw() root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("all files",".*"),("jpg files"...
from typing import Tuple from torch import cuda import torch.nn as nn import torch as th class ResNet(nn.Module): def __init__(self, module): super().__init__() self.module = module def forward(self, inputs): return self.module(inputs) + inputs class ActorCriticNetwork(nn.Module): ...
import random import time from webapi.awebapi import AHTTP # HTTP is synchronous, AHTTP is asynchronous. The former is used for functional testing, the latter for load testing. from webapi.webapi import HTTP class User: '''Represents a user of the app. Creating an object of this class with no parametres c...
import subprocess as sp import os import glob if __name__ == '__main__': Model_dir = '/home/zzhzhao/Model' test_dir = os.path.join(Model_dir, 'tests') source_name = 'original-WRF3.9.1' target_name = 'original-WRF3.9.1-YW_Lake-comp4' WRF_version = 'WRFV3' Modified_wrf_files_path = '/home/zzhzh...
import timeit from lib2to3.fixer_util import Number def principal_period(s): #numerical repetition finder i = (s+s).find(s, 1, -1) return None if i == -1 else s[:i] def primeList(n): #primesieve: returns list of primes nroot = int(n**0.5)+1 print(nroot) sieve = list(range(n+1)) sieve...
"""Utilities for Grappler autoparallel optimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow.core.framework import variable_pb2 from tensorflow.core.protobuf import rewriter_config_pb2 FLAGS = tf.flags.FLAGS def...
"""Veles NN workflow benchmark. """ from __future__ import division import gc import logging import numpy import time from veles import prng from veles.backends import CUDADevice, OpenCLDevice from veles.config import root from veles.dummy import DummyLauncher from veles.loader import FullBatchLoader, IFullBatchLoader ...
m = float(input('Insira a distancia em metros: ')) print('A medida de {}m equivale a:'.format(m)) print('{}Km'.format(m/1000)) print('{}Hm'.format(m/100)) print('{}dam'.format(m/10)) print('{}dm'.format(m*10)) print('{}cm'.format(m*100)) print('{}mm'.format(m*1000))
#! /usr/bin/python import cgi, os import cgitb; cgitb.enable() import csv import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def read_template(filename): with open(filename) as template: return template.read() def blast(from_email,to_email,subject): msg = MIMEMulti...
from classmerge import mergesort from main import sort_given_list from classsum import sumAll print(__init__)
# Generated by Django 3.1.5 on 2021-01-09 18:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('benefits', '0002_benefit_img_file'), ] operations = [ migrations.AddField( model_name='benefit', name='is_verified',...
from django.conf.urls import url from accounts.views import login_view, register_view, logout_view app_name = 'accounts' urlpatterns = [ # login page url(r'^login/', login_view, name="login"), # logout page url(r'^logout/', logout_view, name="logout"), # register page url(r'^register/', regist...
#!/usr/bin/env python # -*- coding: utf-8 -*- # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2016 DataONE # # Licensed under the Apache...
#1235. Maximum Profit in Job Scheduling #We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i]. #You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlappin...
from inmmry import Inmmry while True: print("*"*75) print("1.add 2.view 3.update 4.delete 5.search 6.exit") print("*"*75) ch = int(input("enter choice")) if ch == 1: Inmmry.addContact() elif ch == 2: Inmmry.viewContact() elif ch == 3: Inmmry.updateContact() eli...
import os import pandas as pd from matplotlib import pyplot as plt import seaborn as sns sns.set() path = os.path.dirname(__file__) data_path = os.path.join(path, "..", "..", "data", "master_cr_file.txt") df = pd.read_csv(data_path, sep='\t', low_memory=False) df['period'] = pd.to_datetime(df['period']) number_banks ...
import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import SyncConsumer, AsyncConsumer from channels.db import database_sync_to_async from .models import Thread, ChatMessage User = get_user_model() class TaskConsumer(AsyncConsumer): async def welcome_mess...
#numbers2text def main(): message = input("Please enter the coded message: ") output = "" for nr in message.split(): char = chr(int(nr)) output += char print(output) main() # 66 117 101 110 111 115 32 100 237 97 115 33
from shutil import copyfile from scipy.interpolate import CubicSpline import datetime import os import sys import matplotlib.pyplot as plt import numpy.random as rnd import time from slant import slant from data_preprocess import * from myutil import * def print_image_in_latex_v4( file_to_write, Image_file_prefix, I...