text
stringlengths
38
1.54M
""" This is Lesson 31. Creating a class for an object type Get Programming: Learn to Code with Python """ class Door(object): def __init__(self): self.width = 1 self.height = 1 self.open = False def change_state(self): self.open = not self.open def scale_door(self, factor...
from datetime import datetime # Usually in KITcube tools, we use parameter 'skip-line' to indicate # where we should start reading. But, I think checking data type gives # us a more scalable reader. - NTJ # Fetch data definitions SENSOR_DEF = {} with open('./sensor-definition/jwd.rd.sensors') as f: sensor_dat...
def solution(my_string): answer = [] for char in my_string: if char not in answer: answer.append(char) return ''.join(answer)
import numpy as np import pandas as pd import os scores = np.loadtxt('output.txt') df = pd.read_csv('stage1_sample_submission.csv') df['Probability'] = scores df.to_csv('subp.csv', index=False)
from util.Tokenizer import Tokenizer from util.Index import Index from util import MinHeap import math from collections import Counter class Ranker: """ Applying ranking algorithm from query """ def __init__(self, index, tokenizer): assert isinstance(index, Index) assert isinstance(to...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2018-02-22 16:25 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('newwine', '0027_auto_20180221_2043'), ] operations = [ migrations.AlterFiel...
from datetime import datetime from mock import patch from model_mommy import mommy from django.conf import settings from django.core.urlresolvers import reverse from django.test import TestCase from django.contrib.messages.storage.fallback import FallbackStorage from django.utils import timezone from booking.models i...
import numpy as np import tensorflow as tf import os,ntpath import scipy.misc as misc from math import ceil import json import gen_graph def calculate_shapes(filters,strides,padding): if padding=="SAME": l1_out_height = ceil(50. / float(strides[0][1])) l1_out_width = ceil(50. / float(strides[...
import discord import os from discord.ext import commands, tasks from itertools import cycle from pymongo import MongoClient from utils import get_environment_variable TOKEN = get_environment_variable("DISCORD_BOT_TOKEN") PREFIX = '.' MONGO_CONNECTION_STRING = get_environment_variable("MONGO_CONNECTION_STRING") DB_C...
#!/usr/bin/env python # !-*- coding:utf-8 -*- import redis import time import threading import os from bin.base.tool import JsonFileFunc, Path jff = JsonFileFunc.getInstance() p = Path.getInstance() class RedisFunc: def __init__(self): self.confPath = p.confDirPath + os.sep + "conf.json" redisCo...
# https://codeforces.com/problemset/problem/1506/A import math for _ in range(int(input())): n, m, x = map(int, input().split()) if x % n == 0: row = n else: row = x % n column = math.ceil(x / n) print((row - 1) * m + column)
# Kivy libs import # Python libs import # Personal libs import #Class of a task class AppExercise: # columns used in the csv, in the right order _dtb_columns = [ "appexercise_id", "exercise_id", "workout_id", "rep_time", "rec_time", "series_goal",...
# -*- coding:utf-8 -*-# Author:hankcs# Date: 2018-06-07 15:25 # 《自然语言处理入门》3.5.1 标准化评测 import sys import os # 得到当前根目录 o_path = os.getcwd() # 返回当前工作目录 sys.path.append(o_path) # 添加自己指定的搜索路径 from pyhanlp import * from book.ch03.E_322_msr import msr_dict, msr_train, msr_model, msr_test, msr_output, msr_gold from book.ch03....
#GET 방식 요청 from urllib.parse import urlencode from urllib.request import urlopen query=urlencode({'name':'또치','a':10,'b':20}) f=urlopen('http://www.example.com?' + query) response=f.read() print(response) print('thank you')
import sys import pickle from Player import * from Board import * from GoodAI import * file_name = sys.argv[1] save_file = open(file_name, 'rb') player = pickle.load(save_file) save_file.close() #player = GoodAI('X') board = Board() player.set_sign('X') turn = 1 while not board.check_for_win() and not board.is_ful...
# -*- coding: utf-8 -*- """ Created on Thu Apr 30 20:22:41 2020 @author: voide Prediction avec algorithme knn entrainé avec les mesures statiques """ import pickle import numpy as np from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn import metrics fr...
""" # 만든 모델 불러와서 확인 """ from transformers import BertForMaskedLM, pipeline import torch from transformers.utils.dummy_pt_objects import BertForPreTraining, BertModel from huggingface_konlpy_master.huggingface_konlpy.tokenizers_konlpy import KoNLPyPreTokenizer from huggingface_konlpy_master.huggingface_konlpy.transfor...
import math def radian_to_degree(r): return r * 180 / math.pi def degree_to_radian(degree): return (360 - degree)*math.pi / 180; def inv_radian_to_degree(r): return 360 - radian_to_degree(r) def angle(c, a, b, no_inv=True): if c[1] == b[1] and c[0] < b[0]: return 0 elif c[1] == b[1] and ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from facebook import * import humanRandom def main(username,password): """ Opens FacebookClient and posts random status """ fb = FacebookClient(username,password) humanRandom.searchEngineWaitTime() print("brithdays...") fb.happy_birthdays() ...
__author__ = 'patrickemami' import os # important directories CFG_DIR = 'config' ROCK_CFG_FILE = 'rock_problem-config.json' SYS_CFG_FILE = 'system-config.json' LOG_DIR = 'log' LOG_FILE = 'POMDPy.log' dir = os.path.dirname(__file__) rock_cfg = os.path.join(dir, '..', CFG_DIR, ROCK_CFG_FILE) sys_cfg = os.path.join(dir...
from flask import Blueprint, render_template, abort from jinja2 import TemplateNotFound main = Blueprint('main', __name__, template_folder='templates') @main.route('/') def main_index(): try: return render_template('index.html') except TemplateNotFound: abort(404)
from survey import db from survey.forms import SurveyForm from survey.models import SurveyModel from flask import Blueprint, redirect, render_template, url_for main = Blueprint("main", __name__) @main.route("/", methods=["GET", "POST"]) def render_survey(): form = SurveyForm() if form.validate_on_submit(): ...
#!/usr/bin/env python import rospy from geometry_msgs.msg import Twist from std_msgs.msg import Empty from visualization_msgs.msg import Marker import time def detect_tag(data): #rospy.loginfo(rospy.get_caller_id() + "Detected") #print data.pose global detect detect = 1 def sleep(sec): while(sec and not rospy....
# CEF reader # William Sexton # Last Modified: 4/24/17 # Documentation strengthened by Steve Clark on 5/22/18. """ This is the reader module for the DAS-2018 instance of the DAS-framework. It contains a reader class that is a subclass of AbstractDASReader. The class must contain a method called read. I...
class ElementPresentMixIn(object): """ Support is_element_present_by_* methods for non-javascript drivers. """ def is_element_present_by_css(self, css_selector, wait_time=None): return bool(self.find_by_css(css_selector)) def is_element_not_present_by_css(self, css_selector, wait_time=None): ...
def solution(s): answer = 100000 for n in range(1, len(s)//2 + 2): new_wrd = process(s, n) answer = min(answer, len(new_wrd)) return answer def process(s, n): ret = '' tmp = '' cnt = 0 if s[:n] != s[n: 2*n] or len(s) == 1: return s for _ in range(0, len(s) + n, ...
from tkinter import * from tkinter.filedialog import askopenfile from pygame import mixer from tkinter import messagebox as mb root = Tk() root.title("Music player by Vasu") root.minsize(510,350) root.maxsize(510,350) def openfile(): song = askopenfile(filetypes =[('Music Files', '*.mp3')]) mixer.init() mix...
import os import ROOT conf = dict( muPt = 10, elePt = 10, miniRelIso = 0.4, sip3d = 8, dxy = 0.05, dz = 0.1, ) ttH_skim_cut = ("nMuon + nElectron >= 2 &&" + "Sum$(Muon_pt > {muPt} && Muon_miniPFRelIso_all < {miniRelIso} && Muon_sip3d < {sip3d}) +" ...
from enum import Enum from flask import Flask from flask import request, jsonify from flask_cors import CORS from rule_list import RuleList class Season(Enum): SUMMER = 1 AUTUMN = 2 WINTER = 3 SPRING = 4 class Temperature(Enum): WARM = 1 TEMPERED = 2 class WaterState(Enum): RUNNING = ...
#!/usr/bin/env python f = open('plvars.py', 'rb') varlist = [] for l in f.readlines(): x = l.decode('utf') if ' = ' in x: varlist.append(x.split(' = ')[0]) f.close() g = open('playlistmaker.py', 'rb') h = open('new_pl.py', 'wb') gg = map(lambda x: x.decode('utf'), g.readlines()) for l in gg: for v ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-12-06 19:31 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('login_app', '0001_initial'), ] ...
##method 1 for letter request, delta and rank import sys import os import csv import subprocess import jsonschema import json from datetime import time, datetime, timedelta import itertools from itertools import cycle import matplotlib import matplotlib.pyplot as plt import matplotlib.dates as md import matplotlib as m...
import numpy as np from scipy.io import loadmat, savemat import matplotlib.pyplot as plt from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score train_data = loadmat('train_32x32_pretraitement.mat') test_data = loadmat('test_32x32_pretraitement.mat') lentrain = 1000 len...
from whatsappy import whatsapp whatsapp.login() whatsapp.select_chat('Family Group') whatsapp.remove_from_group('Cousin') # <-- whatsapp.close()
import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn.neighbors import LocalOutlierFactor import seaborn as sns from sklearn.ensemble import IsolationForest sns.set() """ 数据集是计算机的监控数据,主要包含两个特征Latency(延迟)和Throughput(吞吐量) 目标为是否是异常数据: 0为假,1为真。 """ X_train = pd.read_csv('data/X_train.csv') X...
#!/usr/bin/python import sys import random import argparse import numpy as np #parse arguments parser = argparse.ArgumentParser(description = 'Sample N lines from file using reservoir sampling') parser.add_argument('n', metavar='number_of_lines' , help = 'Number of lines to sample', type=int) parser.add_argument('--in...
from __future__ import absolute_import , unicode_literals import random from celery.decorators import task from main.models import * import datetime @task(name="sum_two_numbers") def add(x , y): return x + y @task(name="multiply_two_numbers") def mul(x , y): total = x * (y * random.randint(3 , 100)) ret...
from django.forms.models import model_to_dict from django.http.response import Http404, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import redirect, render from django.views import View from .classes import courses, permissions, sections, users from .classes.permissions import check_permissions...
def MintoN(M, N, i, j): M = M << i mask = (1 << (j - i) + 1) print "{0:b}".format(mask) mask -= 1 print "{0:b}".format(mask) mask = mask << i mask = ~mask print "{0:b}".format(mask) N = N & mask return N | M print "{0:b}".format(MintoN(0b10011, 0b00000000000, 3, 7))
# -*- mode: python -*- a = Analysis(['baboon.py'], pathex=['/Users/guoxin/DropboxNU/Dropbox/My Research/Code/Python/baboon'], hiddenimports=[], hookspath=None, runtime_hooks=None) pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, a.binaries, a....
import bert import tensorflow as tf import tensorflow_hub as hub from bert import optimization from bert import run_classifier from bert import tokenization OUTPUT_DIR = "model/" LABEL_LIST = [0, 1] BERT_MODEL_HUB = "https://tfhub.dev/google/bert_uncased_L-12_H-768_A-12/1" MAX_SEQ_LENGTH = 128 def create_tokenizer_f...
#!/usr/bin/python # Allows to run spectrum and saves data in ASCII from frospy.preprocessing.spectrum import spectrum from frospy.preprocessing.spectrum import taper from frospy.preprocessing.spectrum import printw import sys event = sys.argv[1] # Event name spectrum(data='%s.ahx'%event, syn='%s.ahx.syn.fil'%event, ...
__author__ = 'nsrivas3' class Solution: # @param {integer} n # @return {boolean} def isHappy(self, n): notHappy = 0 iterlist = [] def check(n): sum1 = 0 while n!=0: sum1 = sum1 + (n%10)**2 n = int(n/10) n = sum1 ...
from __future__ import print_function import torch import torch.utils.data from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image from torch.autograd import Variable seed= 10001 cuda = True batch_size = 16 # Random seed t...
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from epic.core.test import CustomTestCase from epic.geoloc.models import GeoLoc from epic.geoloc.utils import CouldNotFindLocation from epic.geoloc.utils import get_best_location class GeoLocTestCase(CustomTestCase): ...
from openpyxl import load_workbook from openpyxl.chart import Series, Reference from openpyxl.styles import Font, Color, PatternFill from copy import deepcopy import numpy as np TEMPLATE_FILE = '../utils/template.xlsx' FINAL_NAME = 'PCIE_ES2.xlsx' DATA_LINE_INDEX = 0 SIGMA_LINE_INDEX = 7 VMIN_LINE_INDEX = 1 START_POIN...
import numpy as np import pickle # data = torch.randn(5, 10, 3, 10, 64, 64) chunked_data = np.random.normal(size=(5, 10, 3, 10, 64, 64)) data = np.random.normal(size=(5, 100, 3, 64, 64)) labels = np.ones((5,)) pickle.dump(chunked_data, open("./_data/chunked_data.p", "wb")) pickle.dump(data, open("./_data/data.p", "w...
from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import include, path, re_path from django.views import defaults as default_views from drf_yasg import openapi from drf_yasg.views import get_schema_view # drf_yasg from rest_framework import per...
__all__ = [ "to_json_string", "from_json_string", "json_fix", "validate_jsonrpc_request", "validate_jsonrpc_response", "jsonrpc_request", "jsonrpc_response" ] import random, string, logging import socket import pkg_resources pkg_resources.require( "simplejson" ) import simplejson to_json_string = simplejson.dumps ...
# 升级步骤 # 1. 下载线上 version 文件 # 2. 读取本地 version 文件 # 3. 比较当前语言下的插件可用更新 # 4. 下载新语言包到暂时位置 # 5. 下载成功后替换本地语言包文件 # 6. 替换成功后重新禁止、启用对应语言包 # 7. 报告更新成功 # 8. 所有更新完成后重写本地 version 文件 import bpy from .utils import get_languagepack_online, get_version_json_online, get_installed_addons, get_version_json_local, set_version...
from io import BytesIO byte_io = BytesIO() # 向内存写入二进制数据 byte_io.write("哈哈".encode("utf-8")) # 读取数据,获取写入内存中的全部数据 data = byte_io.getvalue() print(data) # 解码 content = data.decode("utf-8") print(content)
# coding=utf-8 # Copyleft 2019 project LXRT. import os import collections import random import json import torch import torch.nn as nn from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import numpy as np from param import args from pretrain.qa_answer_table import load_lxmert_qa from vqa_model...
num1=int(input('enter first number to multiply: ')) num2=int(input('enter second number to multiply: ')) sum1= (num1 * num2) print (sum1)
from rest_framework_simplejwt import views as jwt_views from django.urls import path from . import views urlpatterns = [ path('token/create', jwt_views.TokenObtainPairView.as_view()), path('token/refresh/', jwt_views.TokenRefreshView.as_view()), path('token/verify/', jwt_views.TokenVerifyView.as_view()), ...
import numpy as np #KMEANSINITCENTROIDS This function initializes K centroids that are to be #used in K-Means on the dataset X # centroids = KMEANSINITCENTROIDS(X, K) returns K initial centroids to be # used with the K-Means on the dataset X # def kMeansInitCentroids(X, K): randidx = np.random.permutation(X....
import io import os from PIL import Image, ImageChops import argparse try: import picamera except: print("not on pi") import math import datetime from rest_client import ImageRestClient from tensorflow_prediction import predict_image, load_graph def image_entropy(img): """calculate the entropy of an ima...
import os from glob import glob import pickle from nose.tools import eq_ from .. import load from ..utils.py3compat import execfile DATADIR = os.path.join(os.path.dirname(__file__), 'data') def load_data(path): """Load data from python file""" ns = {} execfile(path, ns) return ns['data'] def valu...
from time import sleep from controller import main_controller from util import window_config from view import ui, coursor def main(): # LOGO ui.clear_console() ui.display_board(ui.castle_three.split('\n')) sleep(3.0) # MAIN MENU main_controller.main() if __name__ == '__main__': window_...
# Generated by Django 2.2.4 on 2019-09-26 02:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('quinoas', '0007_sample'), ] operations = [ migrations.AlterField( model_name='sample', name='broken_grain', ...
# Divide-and-conquer algorithm def divide_and_conquer(arr, val): lower_bound = 0 upper_bound = len(arr) - 1 ret_val = None index = (lower_bound + upper_bound) // 2 while lower_bound <= upper_bound: if arr[index] < val: lower_bound = index + 1 elif arr[index] > val: ...
""" Run this after run_analysis.py """ import logging import numpy as np import sys import pickle import tqdm from collections import OrderedDict from astropy.io import fits from astropy.table import Table from scipy.special import logsumexp from scipy import stats import npm_utils as npm def lnprob(y, theta, s_m...
#using elif and try and except for this program try: score = raw_input("Enter Score: ") x = float(score) if x >= 0 and x <= 1.0: if x >= 0.9: print "A" elif x >= 0.8: print "B" elif x >= 0.7: print "C" elif x >= 0.6: print "D" else: print "F" else: print "not in range" #it's not good to...
# This produces a corpus made up of all of the sentences in the brown corpus that are not # included in verified_analogies.csv or verified_non_analogies.csv import os, sys CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(CURRENT_DIR)) from personal import root import nltk from ...
import requests import time import datetime import pandas as pd import csv from matplotlib import pyplot as plt import numpy as np try: # for Python 2.x from StringIO import StringIO except ImportError: # for Python 3.x from io import StringIO def get_bulk_dividends(tickers=[], startdate=1486357200, e...
# Generated by Django 2.0.5 on 2018-11-15 09:41 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('user_profile', '0029_auto_20181115_0940'), ] operations = [ migrations.AlterField( model_name='...
from django.contrib import admin from django.urls import path from django.conf.urls import include from todolist.views import index urlpatterns = [ path('admin/', admin.site.urls), path('todolist/',include('todolist.urls')), #path('',index,name="TodoList"), ]
import actions, world, items, player, tiles import datetime from datetime import timedelta class NPC(object): def __init__(self, x, y): self.x= x self.y= y self.moves = 0 self.dest = None self.last =[] self.nd = {} def check_sked(self, player, world): m...
from flask import Flask# making a flask app, getting the requests from flask_restful import Api # Resource: required data, Api: making api of an flask app, reqparse: parsing the data from flask_jwt import JWT # JWT: key for authentication, jwt_required: decorator for authentication , in this case above GET from securit...
import unittest import import_ipynb import pandas as pd import numpy as np import pandas.testing as pd_testing import numpy.testing as np_testing from sklearn.cluster import KMeans class Test(unittest.TestCase): def setUp(self): import Activity12_1 self.exercises = Activity12_1 self.disp_url = 'https://raw.git...
num1 = input(str("Enter num 1:" )) num2 = input(str("Enter num 2:")) num1 = int(num1) num2 = int(num2) product = num2 * num1 if product > 1000: print("sum of input numbers is ", num1+num2) else: print("product is ", product)
# -*- coding: utf-8 -*- # Andrea Castiella Aguirrezabala # Sharpness DIN 45692 import numpy as np def calc_sharpness(loudness, specificLoudness): # Evitar división entre 0 if loudness == 0: loudness = 1e-8 n = len(specificLoudness) # Zwicker method gz_Z = np.ones(n) for z i...
from __future__ import unicode_literals from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse from django.db.models import Q from django.http import JsonResponse from django.views.generic import FormView from .forms import SearchForm from ra.base.app_settings import RA_ADMIN_SITE_N...
''' 改变世界坐标轴的上轴 ''' # 将y轴变为世界坐标轴的上轴 cmds.upAxis(ax='y') # 将x轴变为世界坐标轴的上轴,并旋转视图 cmds.upAxis(ax='x', rv=True) # 查询当前的世界坐标轴的上轴 cmds.upAxis(q=True, axis=True)
# 定义计算求4位整数每位相加的和的函数 # 1234 --——> 10 def unit_sum(number): ''' 计算整数每位相加的结果 :param number: 4位整数 :return: 每位相加的和 ''' result = number % 10 result += number // 10 % 10 result += number // 100 % 10 result += number // 1000 return result print(unit_sum(1234))
import random from flask import Flask, render_template, request, redirect, session app = Flask(__name__) app.secret_key = 'Secrets' @app.route('/') def index(): if 'gold' not in session: session['gold'] = 0 if 'log' not in session: session['log'] = [] #has to be an array? return render_template('index.html') @...
""""Configuration details""" import os import logging from glob import glob from datetime import timedelta from pathlib import Path from typing import List, Dict, Tuple, Union, Optional import yaml from pydantic import BaseModel, Field logger = logging.getLogger(__name__) my_path = Path(__file__).parent # Defaults ...
import pandas import pickle X = pandas.read_csv("test/features.csv") y = pandas.read_csv("test/target.csv") with open("model.pickle", "rb") as fd: model = pickle.load(fd) r2 = model.score(X, y) with open("metric.txt", "w") as fd: fd.write("r2: {:.2f}\n".format(r2))
# # # Copyright [2015] [Benjamin Marks and Riley Collins] # # 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 # # U...
import re import urllib.parse from typing import Optional, Tuple from django.db import connection from django.utils import timezone from bonobo.accounts.models import CustomUser from bonobo.shops.entities import GeocodedPlace from bonobo.shops.models import Shop class GeocodingUrlParser: def __init__(self, url)...
import UTILS.PROMPI_data as pt import UTILS.ReadParamsTseries as rpt import numpy as np import os import sys import matplotlib.pyplot as plt # read input parameters paramFile = 'param.tseries' params = rpt.ReadParamsTseries(paramFile) datadir = params.getForTseries('tseries')['datadir'] endiannes...
import math import sys INF = 999999999999 def rl(): return sys.stdin.readline().rstrip('\n') for line in sys.stdin: if(len(line.split()) == 1): break k,m = map(int,line.split()) mike = set(map(str,rl().split())) solve = True for _ in range(m): temp = list(map(str,rl().split())...
from flask import Flask from flask_cache import Cache # flask-peewee bindings from flask_peewee.db import Database app = Flask(__name__) app.config.from_object('config.Configuration') cache_config = {'CACHE_TYPE': 'redis', 'CACHE_REDIS_HOST': 'redis'} cache = Cache(app, config=cache_config) cache.ini...
## CSC320 Winter 2016 ## Assignment 2 ## (c) Kyros Kutulakos ## ## DISTRIBUTION OF THIS CODE ANY FORM (ELECTRONIC OR OTHERWISE, ## AS-IS, MODIFIED OR IN PART), WITHOUT PRIOR WRITTEN AUTHORIZATION ## BY THE INSTRUCTOR IS STRICTLY PROHIBITED. VIOLATION OF THIS ## POLICY WILL BE CONSIDERED AN ACT OF ACADEMIC DISHONESTY...
import pandas as pd df = pd.read_csv('bo.txt', sep='\t') df = df[['Total Gross']] print('solo: ', {i[0]: int(i[1].strip()[1:].replace(',', '')) for i in zip(df.index, df['Total Gross'])})
# -*- coding: utf-8 -*- from django.conf.urls import url from . import views urlpatterns = [ url(r'^city/(?P<pk>[0-9]+)/$', views.CityDetailView.as_view(), name='city.detail'), url(r'^citylist/$', views.CityView.as_view(), name='city_list'), url(r'^$', views.index, name='index'), ]
#!/usr/bin/python # -*- coding: utf-8 -*- import urllib2, time #----------------------------------------- serv_id = '16' siteUrl = 'vsetv.cc' httpSiteUrl = 'http://' + siteUrl ttm=0 token='' def getURL(url, Referer = httpSiteUrl): req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10....
import sys head_action = "" head_resource = "" head_detail = "" def write_tail(): global head_action global head_resource global head_detail write_msg = "Finish " + head_action + " " + head_resource + "[" + head_detail + "]\r\n" sys.stdout.write(write_msg) sys.stdout.flush() def write_head...
import numpy import copy import random from Graph import Graph class StringGenerator: depth = 0 length = 0 tensor = [] accept=set({}) state = 0 transition=set({}) def __init__(self,tensor_input,state_input,accept_input,symbol_input): self.tensor = tensor_input self.accept = accept_input self.symbol = symbo...
# Study of the del statement in list comprehensions def del_practice(): example = [1, 2, 3, 4, 5, 6, 7, 8, 9] del example[2:4] return print(example) #Deleta as fatias que são passadas ao argumento if __name__ == '__main__': del_practice()
from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) patronymic = models.CharField...
#!/usr/local/bin/python3 # # See https://theweeklychallenge.org/blog/perl-weekly-challenge-155 # # # Run as: python ch-1.py # print ("3 5 7 13 17 19 23 37")
# Tipos de datos, condicionales, funciones y modulos str_1 = "hola" str_2 = "bienvenido invocador" int_1 = 45 int_2 = 189 flt_1 = 7.9 flt_2 = 78.6 bool_f = False none_1 = None list_1 = list(("pollos", "perros", "conejos")) list_2 = list(range(1, 6)) tuple_1 = tuple(range(1, 11)) tuple_2 = tuple((11,)) s...
from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from kivy.uix.togglebutton import ToggleButton class LedController(App): def tgl_led(self, instance): if instance.state == "down": instance.text = "on" else: instance.text ...
# # Write the inverse function day_num which is given a day name, and returns its number: # test(day_num("Friday"), 5) # test(day_num("Sunday"), 0) #test(day_num(day_name(3)), 3) # test(day_name(day_num("Thursday")), "Thursday") # import sys __author__ = 'petert' def test(actual, expected): """ Compare the actu...
# 显示提示信息 while True: print("1,点菜") print("2.呼叫服务员") print("3.买单") # 用户输入编号 num = int(input("请输入编号")) if num == 1: print("我要点单") elif num == 2: print("呼叫服务员") elif num == 3: print("我要买单")
import torch from reclib.modules import FieldAwareFactorizationLayer from reclib.modules.embedders import LinearEmbedder class FieldAwareFactorizationMachine(torch.nn.Module): """ A pytorch implementation of Field-aware Factorization Machine. Parameters ---------- Reference: Y Juan, ...
from os.path import join from typing_model.models.BERT_models import BaseBERTTyper, ConcatenatedContextBERTTyper, OnlyMentionBERTTyper, OnlyContextBERTTyper from torch.utils.data import DataLoader import pickle from torch.nn import Sigmoid from collections import defaultdict import torch import json model_path = '../...
import pymysql class MysqlClients: def __init__(self, db="wulianwang", h="127.0.0.1", u="root", p="mysqlshanlai", port=3306): """ 初始化MySQL连接 :param db: 数据库名字 :param h: 数据库地址 :param u: 数据库用户名 :param p: 数据库用户密码 :param port: 数据库端口 """ self.host ...
#!/usr/bin/env python import roslib import rospy import math import tf from std_msgs.msg import String from std_msgs.msg import Float64MultiArray from sensor_msgs.msg import JointState from rospy.numpy_msg import numpy_msg import numpy as np #from threading import lock markovMap = [[0, "GNBN", 0, 11, 2, 6], [1, "GBNN"...
import sys args=sys.argv print("type of args:", type(args)) print("type od arge variable",type(args[1])) for i in args: print(i) sum=int(args[1])+int(args[2]) print("sum=",sum)