text
stringlengths
38
1.54M
#!/usr/bin/env python # encoding: utf-8 """ @version: v1.0 @author: zhangyw @site: http://blog.zhangyingwei.com @software: PyCharm @file: image_app.py @time: 2017/11/21 11:42 """ import os from PIL import Image import matplotlib.pyplot as plt import numpy as np base_path = "D:/work/code/zhangyingwei/python/p...
import json # Create your views here. from django.http import HttpResponse from rest_framework.decorators import api_view from rest_framework.renderers import JSONRenderer from .internal.simulator.esmini import record_gif class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSO...
celsius = float(input(f'Informe a temperatura em graus Celsius: ')) fahrenheit = celsius * 1.8 + 32 print(f'A temperatura {celsius} em graus Celsius equivale a {fahrenheit} graus Fahrenheit.')
# Find the length of min subarray that would sum up to a target def minSubArrayLen(nums, s): result_array = [0] * len(nums) for i in range(0, len(nums)): sum = 0 j = i count = 0 while(sum < s and j < len(nums)): sum += nums[j] j += 1 count += ...
import numpy as np from .config_map_enlarger import enlarge def save_data(name, output_name, enlarge_factor, scale_factor): scaled = enlarge(name,enlarge_factor,scale_factor) #grid = 1 - scaled np.save('lib/config_space/data_dir/'+ output_name +'.npy',scaled) def save(name, data): np.save('lib/confi...
import math import numpy as np import tensorflow as tf from tensorflow.contrib.layers.python import layers as tf_layers def _normalize_shape(shape): if isinstance(shape, int): return [shape, shape] assert len(shape) == 2 return shape def get_conv2d_output_shape(input_shape, kernel_shape, str...
from django.contrib import admin from .models import Category,Allergy,Menu admin.site.register(Category) admin.site.register(Allergy) admin.site.register(Menu)
## 6*(9**5) is 354294. So, if the number has 7 digits, ## the sum cant ever be 7 digits Upper = 354294 Ans = 0 for i in range(1,Upper): Num = i Sum = 0 while Num > 0: Digit = Num%10 Num = Num//10 Sum += Digit**5 if Sum == i: print(Sum) Ans += Sum prin...
import pprint # 파일 .text # # 쓰기 # f = open("파일이름", "w") <--- "열고" # f.write("hello world") # f.close() <--- "닫기" 생략 가능 # writelist(x) : x는 리스트의 형태 # w/w+ (읽고, 쓰기 모두 가능) # a : append 추가 # wb : write byte # # 읽기 # f = open("대상이되는 파일", "r") read <---- "열고" # f.read(x) x는 바이트(byte) 단위 # x 생...
from peewee import * from playhouse.postgres_ext import * db = PostgresqlExtDatabase('ks', user='osm', password='osm') class BaseExtModel(Model): class Meta: database = db db_schema = 'grafik' class holidays(BaseExtModel): termin = DateField() opis = CharField(100) wariant = CharField(2) id ...
# -*- coding: utf-8 -*- """ These are tests of `locals_to_globals` and older tests of the techniques used in pytest helper. There are also a couple of early experimental approaches. Mostly stuff related to locals_to_globals and alternatives. """ from __future__ import print_function, division, absolute_import impor...
import logging.config import sqlalchemy from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String # , MetaData, Integer # from sqlalchemy.orm import sessionmaker # from flask_sqlalchemy import SQLAlchemy logger = logging.getLogger(__name__) logger.setLevel("INFO") Base = declarat...
import logging from store.service.store_service import store_type_mapping class StoreTypeCheck(object): _logger = None order = 1 def __init__(self): self._logger = logging.getLogger(__name__) def do_check(self, configuration): conf = configuration.get("STORE") if conf.get("st...
import argparse import os import sys import torch import torchvision import torchvision.transforms as transforms import torch.optim as optim import data_loader import datetime import model_ from torch.backends import cudnn import numpy as np from PIL import ImageFile from utils import TripletMarginLoss, PentaQLoss from...
#!/usr/bin/env python import rospy from std_msgs.msg import String from std_msgs.msg import Int32 from pymodbus.client.sync import ModbusTcpClient color = 0 flag = False def callback_color(data): global color, flag color = data.data flag = True PiSignalPub = rospy.Publisher('PISignalTopic', String, queu...
#!/usr/bin/python ''' Will exclude V-GENEs that are biologically not removes any V-gene segment that isn't biologically possible. Only if atleast 1 biologically possible gene segment remains in this column the CDR3 is included for analysis. ''' import pandas as pd def _acceptable_vgenes(): boilogical_vgenes = [...
from rest_framework import generics, permissions from rest_framework import filters as filters_rf from django_filters import rest_framework as filters from oms_cms.backend.oms_seo.models import Seo, ConnectSSModel, CounterForSite from .serializers import SeoSerializer, SeoCreateSerializer, ConnectSSModelSerializer, Co...
#!/usr/bin/python3.5 import datetime today = datetime.date.today() print(today) crimedate = datetime.date(2013,3,30) print(crimedate) z = today-crimedate # type datetime.timedelta print(z) print(type(z)) # get days only instead of "1708 days, 0:00:00" print(z.days) date_format = "%m/%d/%Y" xxx = datetime.datetime....
from sklearn.preprocessing import OneHotEncoder import numpy as np import pandas as pd from pandas.api.types import CategoricalDtype from copy import deepcopy df = pd.DataFrame({'country': ['russia', 'germany', 'australia','korea','germany'], 'words': ['python', 'is', 'python','cool','me']}) df var...
#!/usr/bin/env python # -*- coding: utf-8 -*- import commands import time from bridgesetting import ConfigAllBridge from common import logger_init, init_iptables_bridge, init_iptables_reverseproxy, init_soft_bypass, init_iptables_transparentbridge if __name__ == '__main__': tag = 0 while tag < 60: st...
#!/usr/bin/env python # # convert gpspoint files to GPX # # TODO: finish symbol normalization # TODO: more complete conversion of fields # import os import sys import re import string import time class Metadata: inputFilename = None outputFilename = None inputFile = None outputFile = None creator ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging import numpy from snisi_core.models.Projects import Cluster # from snisi_core.models.Reporting import ExpectedRepor...
from nose.tools import assert_equal class Node(object): def __init__(self, value): self.value = value self.next_node = None class TestNLast(object): def test(self, sol): assert_equal(sol(2, a), d) print 'Test case passed' def nth_to_last_node(n, head): left_pointer = he...
# 7) Создать вручную и заполнить несколькими строками текстовый файл, в котором каждая строка должна # содержать данные о фирме: название, форма собственности, выручка, издержки. # Пример строки файла: firm_1 ООО 10000 5000. # Необходимо построчно прочитать файл, вычислить прибыль каждой компании, а также # среднюю при...
import requests import records from bs4 import BeautifulSoup from urllib.parse import urljoin from sqlalchemy.exc import IntegrityError db = records.Database('sqlite:///crawler_database.db') db.query('''CREATE TABLE IF NOT EXISTS links ( url text PRIMARY KEY, created_at datetime, ...
# INTEGERS & FLOATS #_________________________________________________________________________________________________________# varint3 = 3 # define integer print(varint3) varint9 = 9 # define integer print(varint9) varfloat = 3.14 #define float print(varfloat) round_varfloat = round(varfloat, 1) # round ...
import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt def make_spectrogram(samples, prnt_spectro=False, fs=44100): """ Takes the samples from songs and converts them to a spectrogram Parameters ------------- samples: np.array samples from a given song, in 1D ar...
original_nrc_dict = { 'abba': 'positive', 'aberrant': 'negative', 'ability': 'positive', 'abolition': 'negative', 'abort': 'negative', 'abovementioned': 'positive', 'abrasion': 'negative', 'abrogate': 'negative', 'absenteeism': 'negative', 'absolute': 'positive', 'absorbed':...
#!/usr/bin/env python3 base = "var addressPoints = [" template = " [{}, {}, \"{}\", {}, {}],\n" template_fuel_begin = "var fuels = {" template_fuel = "\"{}\": {{'min': {}, 'max': {}}},\n" carbu_list = sorted(['Gazole', 'SP95', 'SP98', 'GPLc', 'E10', 'E85']) from lxml import etree import utm output = open('carbus.js...
r""" .. _basic_ferraris: Annotate a session and perform a Ferraris Calibration ===================================================== The following example demonstrates the main workflow we will use when working with `imucal`. We assume that you recorded a Ferraris session with you IMU unit following our :ref:`tutori...
"""How much rain is trapped in Codelandia? No buildings mean no rain is captured:: >>> rain([]) 0 All-same height buildings capture no rain:: >>> rain([10]) 0 >>> rain([10, 10]) 0 >>> rain([10, 10, 10, 10]) 0 If there's nothing between taller buildings, no rain is captured:: ...
#!/usr/bin/env python # _*_coding:utf-8 _*_ ''' 放置程序的配置参数 ''' import os BASE_DIR = os.path.abspath(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) BIND_HOST = '0.0.0.0' BIND_PORT = 9999 ACCOUNT_DB = { 'engine': 'file', # mysql,oracle #accounts.json是存放用户信息的文件 'name' : '%s/conf/...
import pandas as pd import numpy as np from train import train_model from save_model import save_model from load_model import load_model from preprocessing import preprocessing from one_sample import one_sample from pathlib import Path from sklearn.metrics import classification_report dataset = pd.read_csv("Churn_M...
# Generated by Django 2.2.5 on 2020-03-11 05:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ctf', '0012_auto_20200310_1455'), ] operations = [ migrations.RemoveField( model_name='userprofile', name='clg', ...
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: Rotate List Description: Author: God date: 2019/1/17 ------------------------------------------------- Change Activity: 2019/1/17 ------------------------------------------------- """ __au...
#!/usr/local/bin/python # Add a set of design_page_layouts (and possibly a design_page_layout_group) # from a text file and a set of images. # NOTE: this is untested as of 11/18/2013! # This modifies the following database tables: # # page_layout_group insert # page_layout insert # desi...
from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np from sklearn.base import BaseEstimator from sklearn.compose import ColumnTransformer from sklearn.pipeline import make_pipeline import torch from autoPyTorch.pipeline.components.preprocessing.tabular_preprocessing.base_tabular_preprocessi...
#!/usr/bin/env python #import own scripts import Bot_1 as bt import myImage_1 as mi #import numpy import numpy as np from numpy import random # Import OpenCV libraries and tools import cv2 as cv from cv_bridge import CvBridge, CvBridgeError #ROS import rospy import rospkg from std_msgs.msg import String, Float32, ...
from lead_alerts import app from flask import flash, redirect, render_template, request from twilio.base.exceptions import TwilioRestException from .services.twilio_service import TwilioService @app.route('/') def index(): house = { 'title': 'P-Agri Solutions and Services', 'price...
import random ''' problem 5: Calculate f(n), the probability of at least one triple-six when three dice are rolled n times. Determine the smallest value of n necessary for a favorable bet that a triple-six will occur when three dice are rolled n times. ''' def tripleSix(): number = input("Number of times to rol...
from django.test import TestCase # Test view class TestView(TestCase): def test_get_home_page(self): page = self.client.get("/") self.assertEqual(page.status_code, 200) self.assertTemplateUsed(page, 'home.html')
import pytest from uvicore.support import path def test_find_base(): # Test successful path find assumed = __file__.replace('/tests/test_unit/test_support/test_path.py', '') base = path.find_base(__file__) assert base == assumed # Test failed path find (which calls exit()) with pytest.raises(...
import string import random conditions = [ 'New With Tags', 'New Without Tags', 'Slightly Used', ] metals = [ 'Old', 'Plated', 'Gold', 'Silver', 'Other' ] stones = [ 'Diamond', 'Pearl', 'Saphire', 'Ruby', 'Emerald', 'Onix', 'Setreme', 'None' ] for i in...
from . import ScipyBaseSolver from ..objectives import ObjectiveBaseClass class LimitedMemoryBfgs(ScipyBaseSolver): r"""Limited memory variant of BFGS (L-BFGS) See the documentation of scipy for the parameter list and description. Parameters ---------- jac: None Is set automatically to o...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Unittest for querying user. File: test_send_message.py Author: huxuan Email: i(at)huxuan.org """ import random import unittest from wxpusher import WxPusher from . import config class TestSendMessage(unittest.TestCase): """Unittest for querying user.""" @c...
inputarray = [ "10", "10 9.8 8 7.8 7.7 7 6 5 4 2", "200 44 32 24 22 17 15 12 8 4" ] from tools import input, initArrayInputter initArrayInputter(inputarray) import math def mean(l): return sum(l)/len(l) def stddev(l,mu): return math.sqrt(sum([(x-mu)**2 for x in l])/(len(l))) def ro(xl,yl,mux...
#https://stackoverflow.com/questions/27893804/udp-client-server-socket-in-python import socket print ("initialising...") server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_socket.bind(('', 55555)) print ("listening on 55555...") while True: message, address = server_socket.recvfrom(1024) ...
from lib.mobile_web_class import * def test_mobile_web_login(browser, url, email, password): """Tests login on web version of mobile app""" mobile_web = MobileWebClass(browser) mobile_web.mobile_web_login_using_predefined_credentials(browser) mobile_web.goto_mobile_menu(browser)
#FraserHacks application #By Rick and Lindsay #Last edited Dec 11 2019 from tkinter import * import time level = 0 window = Tk() print("hi") f0 = Frame(window) f1 = Frame(window) f2 = Frame(window) f3 = Frame(window) f4 = Frame(window) f5 = Frame(window) f6 = Frame(window) fhImage = PhotoImage(file="FraserHacks-log...
from django.contrib import admin from website import models admin.site.register(models.students) # Register your models here.
# # Copyright 2017 XEBIALABS # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, subli...
def main(): l=[0,0,0,0,0,0,0,0,1,3,5,6,7,7,8,9] regx=0000000013756789 x=00000000137156789 middle=1 while 1: print x temp=x temp*=2 b=False while 1: templist=list(str(temp)) templist.sort() for y in range(len(templist)): ...
class Cat: def __init__(self): print("执行 init 方法") # self.属性名 = 属性初始值 self.name = "Tom" def eat(self): print("%s 爱吃鱼" % self.name) # 使用类名()创建对象的时候,会自动调用__init__方法 tom = Cat() tom.eat() print(tom.name)
''' Created on 2016-05-01 @Sun Tianchen ''' from math import log import psycopg2 import pickle from newspaper import Article from wikicat import sparqlquerier from buildcalais import calais_api ''' count the most frequent wikicat and the leaf level of wordnet cat ontology : dict that maps wikicat/wncat with count '''...
""" Calculate the model features. This code is intended to be an implementation of the feature set described in Tsiouris et al. (2018); unless explicitly noted as such, all deviations from the description there are bugs. """ import numpy as np import scipy.stats import pywt import networkx from bct.algorithms.distanc...
import pytest class TestSample(object): # 测试用例默认以test开头 def test_equal(self): assert 1==1 def test_not_equal(self): assert 1!=0
import networkx as nx import random import copy ''' Method that modifies the Spread of Influence Algorithm(Linear Threshold Model). modification of the algorithm presented in the course slides ''' def calculate_topics_spreading_algorithm(graph, keywords): if not graph.is_directed(): graph = graph.to_dire...
import pytest @pytest.fixture(scope='session') def app(request): from .server import Server server = Server() return server.app
import room, item, character hero_player = character.Player() main_room = room.Room([hero_player], 10, 10) keep_playing = True while keep_playing: print(main_room.__repr__()) inkey = input("Next command: ") if inkey[0] in ['w', 'W']: new_loc = (hero_player.location[0] - 1, hero_player.location[1]) hero_playe...
from os import name from .data import course_dict if name == 'nt': #tkinter for windows from tkinter import Tk,IntVar,Checkbutton,Button,Label,TOP,W def select_semester_classes(): root = Tk() course_variable = dict() def submit(): ...
#Final Project #Group members: Moises, Nicholas, and Sean #December 13, 2016 #CST 205 # ---------Change getSoundsDict and getImagesDict file paths--------- # ---------------------This will change all paths-------------------- soundsDir = "C:\\Users\\Moises\\Desktop\\GitHub\\Immersive-Text-Game-Project\\resources\\soun...
# -*-coding:utf-8-*- import os import time from collections import defaultdict import numpy as np import pandas as pd import xgbfir import xgboost as xgb from bayes_opt import BayesianOptimization """ from keras.models import Sequential from keras.layers import Dense, Dropout from keras.layers.advanced_activations i...
#!/usr/bin/env python import glob from numpy import * import os import pylab as pp def ReadPdb( PdbFile ): """Reads a PDB file with a name provided in the argument. Assumes the PDB file contains only ATOM and TER entries; TER entries are skipped. RETURNS: - Pos, an (Nx3) dimensional...
#Author:xubojoy import os from lightning import Lightning from numpy import random from IPython.core.getipython import get_ipython lgn = Lightning(ipython=True, host='http://public.lightning-viz.org') print(lgn) values = random.rand(100) print(values) # lgn.histogram(values, 10, zoom=False)
#!/usr/bin/python s = open('names.txt', 'r').read() a = s.split('","') a[0] = a[0][1:] a[-1] = a[-1][:-1] a.sort() b = map(lambda y: sum(map(lambda x: ord(x) - ord('A') + 1, y)), a) r = 0L for i in xrange(len(a)): r += (b[i] * (i+1)) print r
""" 2021.03.30. ~ Implementation of "Rethinkng Semantic Segmentation from a Sequence-to-Sequence Perspective with Transformers"(SETR), Sixaio Zheng, etal. 31, Dec, 2020. by Kangmin Park. Lab for Sensor and Modeling, Geoinformatics, Univ. of Seoul. """ from tensorflow.keras.layers import MultiHeadAttention import os os....
import random import math import string full_tiny = {} tiny_full = {} letters = string.ascii_letters + string.digits print(random.randint(0,6200)%62) class Codec: def encode(self,longurl): ans = '' one = '' for i in range(0,6): one = letters[random.randint(0,6200)...
# -*-coding:utf_8 -*- ''' created Date:20161012 Author£:wangjin data1=sqlContext.sql("select sum(case when Date='null'then 1 else 0 end)as DateNULL,sum(case when Date!='null' then 1 else 0 end)as Date1 from dataTrain") data2=sqlContext.sql("select count(*) from dataTrain where Date_received='null'") data11=dataTr...
from numba import jit @jit def is_jamcoin(C): divisors = [0] * len(C) for i in range(len(C)): # there are still over 5000 jamcoins for d in range(2, min(int(C[i]**0.5)+1, 100)): if C[i] % d == 0: divisors[i] = d break if not 0 < divisors[i]: ...
# _*_coding:utf-8_*_ def search(li,item): if len(li) == 0 : return False mid = len(li)//2 if li[mid] == item: return True elif item > li[mid]: return search(li[mid+1:], item) else: return search(li[:mid], item) if __name__ == '__main__': l = [1,2,4,6,2,1,6] ...
from cas.rule import RuleList from cas.operable import Operable class Expr(Operable): def __new__(cls, *args): label = fr'{cls.__name__}({", ".join(map(repr, args))})' obj = super().__new__(cls, label) if not hasattr(obj, 'operator'): obj.operator = cls obj.args = ar...
#!/usr/bin/env python import cmath jw = complex(0, 2.0 * cmath.pi * 13.56e6) def ZR(R): return R def ZL(L): return jw * L def ZC(C): return 1.0 / (jw * C) # die Werte Zs = (ZR(100), ZR(25), ZC(220e-12)) Vs = (13.0, 6.56, 14.1) def relation(v): """relations between values""" relations = [] f...
# Generated by Django 3.0.1 on 2020-02-24 18:37 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('constructor', '0012_auto_20200224_1834'), ] operations = [ migrations.RenameField( model_name='biscuit', old_name='fillColor...
# -*- coding: utf-8 -*- # @Time : 2021/8/3 17:06 # @Author : Jamerri # @File : __init__.py cars = ['audi', 'bwm', 'subaru', 'toyota'] for car in cars: if car == 'bwm': print(car.upper()) else: print(car.title())
""" Wiki mods exporter Overview =============================================================================== +----------+------------------------------------------------------------------+ | Path | PyPoE/cli/exporter/wiki/parsers/mods.py | +----------+----------------------------------...
from django.conf.urls import patterns, include, url, handler404, handler500 from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'tpages.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^tpages/admin', include(admin.site.urls)), url(r'^tpages...
from flask import Flask from flask.ext.restful import Api from flask.ext.restful.utils import cors from api import config from api.calllog.CallLogAPI import CallLogAPI app = Flask(__name__) app.config.from_object(config) api = Api(app) # api.method_decorators = [cors.crossdomain(origin='*')] # public services api.a...
### Boss ### class Boss: def __init__(self, couleur): self.couleur=couleur self.libre = True
#!/usr/bin/env python # -*- coding: utf8 -*- # https://youtu.be/DdHMnHeX5rY # wxPython #7: механизм обработки событий - Bind, Unbind # wx.EVT_BUTTON – событие, генерируемое виджетом wx.Button; # wx.EVT_MENU – событие, генерируемое меню; # wx.EVT_TEXT – событие, генерируемое wx.TextCtrl; # wx.EVT_TOOL – событие, гене...
#!/usr/bin/env python #coding:utf-8 # 列表list的9个方法[解释]: #1 ''' l.append? Docstring: L.append(object) -- append object to end Type: builtin_function_or_method (1)追加对象到末尾(一个参数) (2)无返回值 (3)示例: l = [] l.append('hello') l.append(123) l.append(True) l.append([1,2,'rr']) p...
''' Hackerrank: https://www.hackerrank.com/challenges/equal/problem using solution mentioned in discussion area. reverse thinking: "dispatch chocolates" => "taken away chocolates" until 0 or equal ''' import sys, copy from collections import defaultdict memory = defaultdict(int) minimum_ops_count = None def ops_to...
inputNumber=input('Enter the input number !') mapNumber={ 1 : "one", 2 : "two", 3 : "three", 4 : "four", 5 : "five", 6 : "six", 7 : "seven", 8 : "eight", 9 : "nine", 0 : "😢" } stringTemp="" for int1 in inputNumber: tempInt=int(int1) stringTemp = stringTemp +" " +mapNumbe...
BASE_CHARGE = 15 SUPPORT_911 = 0.44 AIR_TIME = 0.25 TEXT_MESSAGE = 0.15 TAX = 0.05 air_time = int(input('Enter the number of minutes: ')) text_messages = int(input('Enter the number of text messages: ')) total = BASE_CHARGE + SUPPORT_911 print(f'Base charge: {BASE_CHARGE}') if air_time > 50: additional_minutes =...
# Copyright 2015 - Alcatel-Lucent # Copyright 2016 - 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 applicabl...
# test the functions train_set = open('../data/train.txt','r').readlines() data=[] for i in train_set: tmp=[] a=i.strip('\t\n').split('\t') for j in a: tmp.append(float(j)) data.append(tmp) print data[0][85]
# -*- coding: utf-8 -*- from api.mixins import MultiSerializerListRetrieveMix from property.models import Property from rest_framework import permissions from . import serializers class PropertyViewSet(MultiSerializerListRetrieveMix): queryset = Property.objects.all() serializer_class = serializers.Propert...
# coding=utf-8 ''' http://www.runoob.com/python/python-numbers.html ''' ''' 1.Number 数据类型用于存储数值。不允许改变。 (1)python支持四种不同的数值类型: int(整型)——通常被称为是整型或整数,是正或负整数,不带小数点。 long integers(长整型)——无限大小的整数,整数最后是一个大写或小写的L。 floating point real values(浮点型)——浮点型由整数部分与小数部分组成。 complex numbers(负数)——复数由实数部分和虚数部分构成,可...
def count_smileys(arr): counter = 0 valid_faces = [':)', ':-)', ':~)', ':D', ':-D', ':~D', ';)', ';-)', ';~)', ';D', ';-D', ';~D'] for i in arr: if i in valid_faces: counter += 1 return counter
from django.shortcuts import render '''def está criando uma função, chamada index; request é requisição; return significa retornar a pg, render renderizada, neste caso a pg index.html ''' def index(request): return render(request, 'index.html'), def sobre(request): return render(request, 'sobre.html'),
""" Usage: python_visitor_gui.py This script shows how one can implement visitors in pure python and inject them into OpenGM solver. ( not all OpenGM solvers support this kind of code injection ) """ import opengm import numpy import matplotlib from matplotlib import pyplot as plt shape=[100,100] numLabels=...
import roslib; roslib.load_manifest('hip') from hip import SubTask def cup_suggester(current_state, goal, symbols): for x in [1, 2, 3]: yield x def bowl_suggester(current_state, goal, symbols): for x in ['a', 'b', 'c']: yield x class PickupObject(SubTask): def __init__(self): SubT...
# result = [] # def permutation(data,i,n): # if i == n: # result.append("".join(data)) #['A','B','C'] # for j in range(i,n+1): # data[i],data[j] = data[j],data[i] # permutation(data,i+1,n) # data[i],data[j] = data[j],data[i] #backtraking # data = "ABC" #['A','B','C'] # i = 0 #...
import logging from collections import defaultdict import torch from torch.distributions import Normal, kl_divergence, Bernoulli from torch.nn import functional as F from torch.optim import Adam from torch.utils.tensorboard import SummaryWriter from .config import BaseConfig from .env import EnvBatcher from .memory i...
from belt_app.config.mysqlconnection import connectToMySQL from flask import flash from belt_app.models import author, user, review class Book: def __init__(self, data): self.id = data['id'] self.title = data['title'] self.user_id = data['user_id'] self.author_id = data['author_id'...
tokens = re.split(ur'(?u)[^-\w]', raw) except TypeError: tokens = raw while u'' in tokens: tokens.remove(u'') try: matches = re.split(ur'(?u)[^-\w]', query) except TypeError: tokens = query while u'' in matches: matches.remove(u'') for token in tok...
# Teste seu codigo aos poucos. # Nao teste tudo no final, pois fica mais dificil de identificar erros. # Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo. var1 = int(input("Digite um numero: ")) var2 = int(input("Digite um numero: ")) var3 = int(input("Digite um numero: ")) menor = min(var1,...
""" Simple handlers for serializers. """ BINARY_PROTOCOL = 'wamp.2.msgpack' JSON_PROTOCOL = 'wamp.2.json' NONE_PROTOCOL = ''
import json from strsimpy import Levenshtein def link_ecoregion(): species_ecoregion_link_dict = dict() levenshtein_obj = Levenshtein() with open('ecoregion_info.json', 'r') as f_in, open('eol_mammal_trait.json', 'r') as f_in2, \ open('all_mammals.json') as f_in3: ecoregion_info_dict =...
def binary_search_sub(a, x, start, end): if start > end: return -1 mid = (start + end) // 2 if x == a[mid]: return mid elif x > a[mid]: return binary_search_sub(a, x, mid+1, end) else: return binary_search_sub(a, x, start, mid - 1) return -1 def bin...
#! /usr/bin/env python # encoding: utf-8 try: from setuptools import setup except ImportError: from distutils.core import setup setup(name='PyVimeo', version='1.0.2', description='Simple interaction with the Vimeo API.', url='https://developer.vimeo.com/', author='Vimeo', author_email='sup...