text
stringlengths
38
1.54M
from tkinter import * import tkinter.messagebox as box # Use app name throughout appname='Thorganizer' window = Tk() window.title(appname) label = Label(window, text='What is running through your mind?') label.pack(padx=200, pady=50) frame = Frame(window) entry = Entry(frame, width=200) listbox = Listbox(frame) lis...
from django.db import models # Create your models here. class Clicks(models.Model): clicked = models.IntegerField(default=0) def __str__(self): return f"Button Clicked {self.clicked} times"
from math import log2 def cal(l,num): r=0 for i in l: i.append(i[0]-i[1]) r-=i[0]/num*(i[1]/i[0]*log2(i[1]/i[0])+i[2]/i[0]*log2(i[2]/i[0])) return r height=-(3/8*(2/3*log2(2/3)+1/3*log2(1/3))+2/8*0+3/8*(2/3*log2(2/3)+1/3*log2(1/3))) print(height) he=[[3,2],[2,0.0000001],[3,2]] bu=[[2,1],[3,2...
# with open("blalblb.txt") as f: # read_file = f.read() # print(read_file) ## # print(f.read()) class OurOpen: def __init__(self, file_path): self._file_path = file_path def __enter__(self): print('Im enter') self.file = open(self._file_path) return file def __exit_...
import re import json # https://api.github.com/emojis with open("emoji.json", "r") as h: data = json.load(h) URL = re.compile(r"/([^/.]+).png") emojis = {} for name, url in data.items(): match = URL.search(url) if not match: print(url) continue codes = match[1].split('-') try: ...
import pytest from apitest.core.helpers import make_directoriable def test_make_directoriable_ok_case(): assert make_directoriable("Hello World guy!") == "hello_world_guy" def test_make_directoriable_underline(): assert make_directoriable("Hello-World-guy!") == "hello_world_guy" def test_make_directoriab...
from src.loaders.abstract_loader import AbstractVideoLoader import cv2 from src.models import VideoMetaInfo, FrameInfo, ColorSpace, Frame, FrameBatch class SimpleVideoLoader(AbstractVideoLoader): def __init__(self, video_metadata: VideoMetaInfo, *args, **kwargs): super().__init__(video_metadata, *args, *...
# Generated by Django 2.1.2 on 2018-11-14 15:31 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('accounts', '0021_auto_20181114_1523'), ] operations = [ migrations.AlterField( model_name='post...
import unittest import tempfile import os from maruti import sizes class DeepfakeTest(unittest.TestCase): def test_byte_to_mb(self): self.assertEqual(sizes.byte_to_mb(1024*1024), 1) self.assertAlmostEqual(sizes.byte_to_mb(1024), 0.0009765624, delta=1e-8) def te...
import random class robot: def __init__(self): """Our robot constructer.""" self.moods = ["neutral","angry","happy","'kill all humans'"] self.eyecolors = ["off","red","green","electric crimson"] self.mood = "" self.eyecolor = "" def changemood(self): r = ra...
# a116_buggy_image.py import turtle as trtl # instead of a descriptive name of the turtle such as painter, # a less useful variable name x is used spider = trtl.Turtle() spider.pensize(40) spider.circle(20) w = 6 y = 70 z = 380 / w spider.pensize(5) n = 0 while (n < w): spider.goto(0, 0) spider.setheading(z ...
valor1 = int(input("primeiro valor: ")) valor2 = int(input("Ultimo valor: ")) valor_potencia = int(input("valor potência: ")) for i in range(valor1, valor2+1): print("i = {}^{} = {}".format(i,valor_potencia,(i ** valor_potencia)))
from django.contrib import admin from .models import Media, Platform, Review admin.site.register(Platform) admin.site.register(Media) admin.site.register(Review)
""" Simple Baseline Model for AV-Sync. Organinzed in PyTorch Lightning Flatten both audio and video features; concat them and feed into sequential linear layers. """ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import pytorch_lightning as pl # from chord_rec.models.seq2seq.Seq2...
import requests import json from mutagen.mp3 import MP3 from mutagen.easyid3 import EasyID3 from mutagen.id3 import ID3, APIC from auth import getToken def getSpotify(): # Spotify Api call for meta data token = getToken() f = open('YT_results.json') yt_result = json.load(f) track = yt_result['...
# -*- coding: utf-8 -*- ''' from gluon.sql import DAL, Field db1=DAL('firebird://sysdba:masterkey@127.0.0.1:3050//fdb/erp.fdb', migrate_enabled=False, ignore_field_case=True, entity_quoting=False ) ''' data = IS_NULL_OR(IS_DATE(format=T("%d/%m/%Y"))) TIPOCLIENTE = {'J':"Jurídica","F":"Física"} CLIENTEFINAL = {'S'...
from flask import Flask, render_template serious1 = Flask(__name__) @serious1.route("/bmi/<int:weight>/<int:height>") def bmi(weight, height): bmi = weight / (height/100)**2 a = "" if bmi< 16: a = 'Severely underweight' elif 16 <= bmi < 18.5: a = 'Underweight' elif 18.5 <= bmi < 25...
from util import * def parse(code, references): statements = code.split(';') output = '' for statement in statements: cellPointer = 0 statement = statement.strip() op = '+' splitByPlusOrMinusEquals = stripAll(statement.split('+=')) if len(splitByPlusOrMinus...
""" Reverse a string """ def reverseString(string): #base case if len(string) == 0: return string else: return reverseString(string[1:]) + string[0] if __name__ == '__main__': string = "hello world" print(reverseString(string))
# This is the message sender import os from socket import * from fractions import gcd from random import randrange from collections import namedtuple from math import log from binascii import hexlify, unhexlify from threading import Thread import tkinter # LWZ Compression def compress(uncompressed): """Compress a...
# MIT License # # Copyright (c) 2016-2023 AnonymousDapper # from __future__ import annotations import asyncio import sys from pathlib import Path from typing import Literal, Optional, Union import aiohttp import arrow import discord import mystbin import tomli from discord.ext import commands from cogs.utils impor...
def mul(): l=[3,5,6,7,-8] i=0 mul=1 while i<len(l): mul=mul*l[i] i=i+1 print(mul) mul()
# Expectation from correct syntax for each row: # - Labels comes first. could be more than one in theory. # - OP code comes after label. # - Operands comes last. # - Defined labels must end with ":" # - # # TODO: ///////////////////////////////////////////////////////////////// # Fixxa så vi appendar till listan istäl...
t = int(input("Digite uma temperatura em graus Celsius: ")) def loop_for(): for c in range(t-10, t+11): f = c * 1.8 + 32 print("%.dº Celsius = %.dº Farenheit" % (c, f)) def loop_while(): c = t - 10 while c <= t + 10: f = c * 1.8 + 32 print("%.dº Celsius = %...
# coding: utf-8 #!/usr/bin/env python from torneira.controller import BaseController, render_to_extension from twittface.models.usuario import Usuario from torneira.core.meta import TorneiraSession from sqlalchemy.orm.exc import NoResultFound from tornado.web import HTTPError import tweepy import math import settings...
lists = ['start', 1, 2, 3, 4, 5, 6, 7, 8, 9, 'end'] print(lists[:]) print(lists[0:5]) print(lists[6:8]) print(lists[:6]) print(lists[5:]) print(lists[-1]) print(lists[-6:-1]) print(lists[0:10:2]) # [starting_index : ending_index : increment] print(lists[::-1]) # reverse showing print("\nString Slicing...
import nltk from nltk.tokenize import sent_tokenize, word_tokenize from nltk.corpus import stopwords import pymorphy2 morph = pymorphy2.MorphAnalyzer() #print (stopwords.words("russian")) #ru_stops = set(stopwords.words('russian')) #ru_stops.add("."); #ru_stops.add(","); #ru_stops.add(")"); #ru_stops.add("("); stops =...
import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D def midpoints(x): '''Used in the function plot_voxel()''' sl = () for i in range(x.ndim): x = (x[sl + np.index_exp[:-1]] + x[sl + np.index_exp[1:]]) / 2.0 sl += np.index_exp[:] return ...
import random ITER_AMOUNT = 100 def mul(a, b, modulo): return ((a % modulo) * (b % modulo)) % modulo def modulo_binary_exp(x, n, modulo): if n == 0: return 1 if n % 2 == 0: x_pow = modulo_binary_exp(x, n // 2, modulo) return mul(x_pow, x_pow, modulo) else: return mul...
from string import ascii_lowercase, ascii_uppercase text = 'dkghokdghopAAAAAAAfghgfbnvbnretwwquouipiuopAAAAdkhotkyr0k59-kk53gki53g53k5klk%^%^%_&)%_+)_+)$_+)%^$%$)(^+_)%(&_(' new_text = '' for elem in text: if elem in ascii_lowercase: new_text += str(elem) if elem in ascii_uppercase: new_text += str(ele...
from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): # object level permission to only allow the use of the object to edit it # assumes the model instalnce has an owner attribute def has_object_permisson(self, request, view, obj): if request.method in permis...
import numpy as np import gspread import pandas as pd from google.oauth2.service_account import Credentials import os import selenium from selenium import webdriver import time import io import requests from webdriver_manager.firefox import GeckoDriverManager from selenium.webdriver.common.by import By fro...
from Lista import Lista ListaEjemplo = Lista() ListaEjemplo.insert_node("Prueba1", 12) ListaEjemplo.insert_node("Prueba2", "Valor2") ListaEjemplo.insert_node("Prueba3", 12) print(ListaEjemplo.get_size()) print(ListaEjemplo.get_node(0).get_contenido())
#!/usr/bin/python # -*- coding: utf-8 -*- ''' 1.16 筛选序列中的元素 Created on 2016年7月24日 @author: wang ''' mylist = [1,4,-5,10,-7,2,3,-1] print [n for n in mylist if n > 0]#列表推导式 print [n for n in mylist if n < 0] pos = (n for n in mylist if n > 0)#生成器表达式 print pos for x in pos: print(x) values = ...
#!/usr/bin/env python __author__ = 'rgolla' import argparse parser = argparse.ArgumentParser() parser.add_argument( '-i', action='store', dest='input', help = 'Text file that contains the whitespace seperated "source_id image_url" lines for which the activity that we wish to train for is presen...
# ''' # Return the number of letter occorrances in a string. # # >>>count_letter("i", "Antidisestablishmentterianism") # # >>>count_letter("p", "Pneumonoultramicroscopicsilicovolcanoconiosis") # ''' # def count_letter(char, word): # for letter in word: def count_letter(char, word): letter_count = 0 for l...
import math f = open('p099_base_exp.txt', 'r') m = 0 count = 0 lineNum = 0 for line in f: count += 1 a = int(line.split(',')[0]) b = int(line.split(',')[1]) if m < b*math.log(a): m = b*math.log(a) lineNum = count print lineNum
#to run spark-submit spark.py #Serenitylesa4411! from pyspark.sql import SparkSession from pyspark.sql.types import StructType, StructField from pyspark.sql.types import DoubleType, IntegerType, StringType # from pyspark.sql.functions import * # from pyspark.sql.functions import mean as _mean, stddev as _stddev, col...
# coding: utf-8 """ 난이도 : 1 문제 : 양의 정수 n과 m이 주어진다. (1000 10) n원을 m명에게 정확히 분배해야 한다. 만약 10원을 3명에게 배분하면 3원씩 배분하고 1원이 남는다. 첫 줄에 얼마씩 배분할 수 있는지, 둘째 줄에 배분하고 남는돈을 1원단위로 출력. 알고리즘 : n을 m으로 나눈 몫을 첫줄에 출력하고, 나머지를 둘째 줄에 출력 """ m,n=map(int,input().split()) print(*[m//n,m%n],sep='\n')
"""2a: RNN""" """I have tried different dense model architecture but best one was this which is 2nd dense with 32 hidden units""" """Dropout also helped to improve model. I kept playing with dropouts and additional dropout layer until i get least loss""" """But when i rerun model it gives me different kind of test_loss...
from offsetbasedgraph import IntervalCollection, Interval, NumpyIndexedInterval from collections import defaultdict from offsetbasedgraph import IndexedInterval import logging class HaploTyper: """ Simple naive haplotyper """ def __init__(self, graph, intervals): assert isinstance(intervals, I...
import sys sys.path.append("..") import uuid from wizhelper.WizServerUrl import WizServerUrl ## class WizObject: '''wizobject''' def __init__(self): self.guid = uuid.uuid1() def printWizObject(self): print(self.guid) print(WizServerUrl())
import json import os from datetime import datetime import sys sys.path.append("../") from causal_graphs.graph_visualization import visualize_graph from causal_graphs.graph_export import load_graph from causal_graphs.graph_real_world import load_graph_file from causal_graphs.graph_definition import CausalDAG from caus...
import os import re import requests from tqdm import tqdm def save_file_at_new_dir(new_dir_path, new_filename, new_file_content, mode='w'): os.makedirs(new_dir_path, exist_ok=True) with open(os.path.join(new_dir_path, new_filename), m...
import os #定义文件生成器 #生成一个空文件 def createini(): os.system("cd.>%s.ini" %ininame) first = open('%s.ini' %ininame,'w') first.close() #定义数据创建器 def createdata(ininame,hajime,owari,hitoashi): datas = [] while hajime <= owari: datas.append(hajime) hajime = hajime + hitoashi ...
""" demo09_cv.py 词袋模型 """ import nltk.tokenize as tk import sklearn.feature_extraction.text as ft doc = 'The brown dog is running. ' \ 'The black dog is in the black room. ' \ 'Running in the room is forbidden.' # 对doc按照句子进行拆分 sents = tk.sent_tokenize(doc) # 构建词袋模型 cv = ft.CountVectorizer()...
#!/usr/bin/env python # $Id$ ## ## This file is part of pyFormex 0.7.1 Release Sat May 24 13:26:21 2008 ## pyFormex is a Python implementation of Formex algebra ## Website: http://pyformex.berlios.de/ ## Copyright (C) Benedict Verhegghe (benedict.verhegghe@ugent.be) ## ## This program is distributed under the GNU Gene...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # SUMKAM.NET # # GIMP Python-Fu скрипт обработки изображений # для каталога товаров. # # Считывает файл конфигурации cfgHomeFile. # Увеличивает контраст на значение val. from gimpfu import * import os import ConfigParser def plugin_func(): cfgHomeFile = "~/sumkamnet/...
from django.contrib import admin from locations.models import * @admin.register(Country) class CountryAdmin(admin.ModelAdmin): list_display = ['name'] search_fields = ['name'] @admin.register(City) class CityAdmin(admin.ModelAdmin): list_display = ['name'] search_fields = ['name'] @admin.register(Location) cla...
# TODO: Create CSV matrix files for existing data import common.constants as cn import common_python.constants as ccn from common_python.testing import helpers from common_python.classifier import feature_analyzer import classifier.main_case_classifier as main import numpy as np import os import pandas as pd import sh...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jun 13 11:58:41 2021 @author: satheesh """ def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' # Your code here a = ''.join(sorted(aStr)) ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ################################################ #a simple test . class ListNode2: def __init__(self, x): self.val = x self.next = None self.add=self.val*5 def addcount(self): print "begin" t=self.add*4 return t a=ListNode2(4) print a.add print a.addc...
# Add the upper directory (where the nodebox module is) to the search path. import os, sys; sys.path.insert(0, os.path.join("..","..")) from nodebox.graphics import * # In the previous examples, drawing occurs directly to the canvas. # It is also possible to draw into different layers, # and then transform / animate...
import argparse import logging import math import sys from ignite.metrics import Loss from tensorboardX import SummaryWriter import torch from torch.nn import ModuleList from torch.utils import data logging.basicConfig( level=logging.INFO, format="%(asctime)s | %(name)s | %(levelname)s | %(message)s", dat...
import numpy import math u = [1,-1,1,-1,1,-1,1,-1,1,-1, 1] def evalPoly(f, n): s = 0 for i in range(0, len(f)): s += f[i] * (n ** (i)) return s def getPoly(seq): a = numpy.matrix([ [n ** j for j in range(0, len(seq))] for n in range(1, len(seq) + 1)]) b = numpy.array(seq) ...
def patternToNumber(pattern): num = 0 k = len(pattern) - 1 gene_dict = {"A":0, "C":1, "G":2, "T":3} for i in pattern: num += gene_dict[i] * pow(4, k) k -= 1 return num def numberToPattern(index, k): gene_dict_reverse = {0:"A", 1:"C", 2:"G", 3:"T"} p = "" q = 0 k = k ...
from unittest import TestCase import numpy as np from com.seregy77.evnn.spea2.individual import Individual from com.seregy77.evnn.spea2.network_parameter import LayerParameter def init_weights(): layers_config = [784, 50, 50, 10] max_weight = 0.3 * 1.0 min_weight = -0.3 * 1.0 max_bias = 0.3 * 1.0 ...
# -*- encoding: utf-8 -*- import requests import re import sys import json import time import datetime aid='44625717' #就是av号 page=0 #我们一般说的“第xP”里的“x”就是这个值 date_start='2019-02-25' #起止日期 date_end='2019-03-01' cookie_header={ 'Cookie': #填一个你的登录Cookie上去,隐私相关,注意不要泄露 } class bilibili: class vid...
#!/usr/bin/env python3 # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. i...
import helper from flask import Flask, request, Response import json app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' @app.route('/record/new', methods=['POST']) def add_record(): # Get record from the POST body # only pass '{"contact_name": "Name", "contact_email_id": "ma...
# -*- coding: utf-8 -*- """ @author: Dhruv This python script contains functions to perform pre-processing on the uploaded image. Attributes of the image such as brightness and constrast are adjusted in order to enhance the accuracy of the OCR process. Three operations, namely grayscaling, thresholding and nois...
# code_user.py # Mike Solak # 22 Jan 2020 from cryptography.fernet import Fernet import key_from_pass def encode_account(acc_list: list, key: bytes): '''acc_list = ['username', 'password'] will then return acc_list but encoded ''' f = Fernet(key) # key created from password index = 0 while ...
import sys sys.stderr.write('this is a error message\n') sys.stderr.flush() sys.stdout.write('this is a standard text\n') print(sys.argv) if len(sys.argv)>1: print(sys.argv[1])
shopping = [ ('Iphone',5800), ('mac pro',9800), ('bike',800), ('watch',10600), ('coffee',31), ('alex',120) ] # def info(): # tem_info={} # with open('info.txt','r',encoding='utf-8') as f: # line = f.readline() # info_list = line.rstrip().split('') # tem_info[info...
#!/usr/bin/env python # encoding: utf-8 # Daniele Trifiro` # brethil@phy.olemiss.edu ''' This program is used to perform PCA and cluster in the principal component space data from `pcat.finder` It's important to note that, even if this is written to use GMM, with a few changes, every clustering algorithm (currently 'g...
import os import pandas as pd import geopandas as gpd FOLDER_RAW = os.getenv('DIR_DATA_RAW') FOLDER_PROCESSED = os.getenv('DIR_DATA_PROCESSED') DATA_LIGHT = 'geo_export_e87e8b43-cf73-48e4-ad5c-692f56b45394.shp' shp_light = gpd.read_file(filename=FOLDER_RAW + "/camden_street_lighting/" + DATA_LIGHT) # aggregate to ge...
#!/usr/bin/env python #coding=utf-8 import urllib2 import urllib import re class Tool: #删除img标签和7位空格 removeImg=re.compile('<img.*?>|\s{7}') #删除超链接 removeAddr=re.compile('<a.*?>|</a>') #替换换行标签为\n replaceLine=re.compile('<tr>|<div>|</div>|</p>') #将制表<td>替换为\t ...
# -*- encoding: utf-8 -*- from pygmatic_segmenter.types import Text import re class AbbreviationReplacer: """This class searches for periods within an abbreviation and replaces the periods.""" def __init__(self, text, language): self.text = Text(text) self.language = language def r...
# 线程池和进程池 from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor def fn(name): for i in range(1000): print(name, i) if __name__ == '__main__': #  创建线程池 50 个 with ThreadPoolExecutor(50) as t: for i in range(100): t.submit(fn, name=f"线程{i}") print("done")
-X FMLP -Q 0 -L 3 88 300 -X FMLP -Q 0 -L 3 86 250 -X FMLP -Q 0 -L 3 73 250 -X FMLP -Q 0 -L 3 58 200 -X FMLP -Q 1 -L 1 46 175 -X FMLP -Q 1 -L 1 45 200 -X FMLP -Q 1 -L 1 33 100 -X FMLP -Q 2 -L 1 27 150 -X FMLP -Q 2 -L 1 27 100 -X FMLP -Q 2 -L 1 23 100 -X FMLP -Q 3 -L 1 18 300 -X FMLP -Q ...
import urllib.request import time from bs4 import BeautifulSoup from Task4.MatrixTools import MatrixTools from Task4.MatrixToolsOld import MatrixToolsOld if __name__ == '__main__': start_time = time.time() tools = MatrixTools("http://en.wikipedia.org/", 100) # tools.makeMatrix() tools.countPagerank()...
from typing import * class Solution: def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: be = [] for b in bookings: be.append((b[0],0,b[2])) be.append((b[1],1,b[2])) be.sort() rc,cr = [0]*(n+1),0 #print(rc) for i,(f,sR...
""" Import Python modules """ import os """ Import Django modules """ from django.db import models """ Import Django settings """ from emp.settings import MEDIA_ROOT """ Import Models """ from django.contrib.auth.models import User """ Import from 3rd party Django modules """ from taggit.managers import Taggab...
from django.test import TestCase from django.contrib.auth import get_user_model class UserTests(TestCase): def test_create_interviewer(self): """Test creating a new user""" email = "test@gmail.com" username = "test" password = "test1234" user = get_user_model().objects.cre...
""" -- Theano implementation of a single de-noising autoencoder, trained on reconstruction error -- Pieces of this code borrow from code snippets on deeplearning.net NOTES: -- Imports tt_algebra module, which performs all symbolic algebra required to generate gradient updates -- Function compilation to execute the SG...
from QTA.Signals.ClassifyBar import ClassifyBar from QTA.Execution.SetEntryExits import SetEntryExits import QTA.DataConfiguration.RetrieveData as RD import datetime as dt import math as m ################################ # Unit Tests (SetEntryExits) ################################ def test_set_entry_price_from_buy_...
#!/usr/bin/env python # verify types of CRISPR-Cas systems / verify using predictions import sys import os import operator import subprocess cmd = sys.argv[0] resultdir, resultfile = "", "" genome = True for idx in range(len(sys.argv)): if (sys.argv[idx] == "-d") and (len(sys.argv) > idx + 1): resultdir = sys.argv...
# Generated by Django 3.0.7 on 2020-09-02 18:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('product', '0005_migration_product'), ] operations = [ migrations.AddField( model_name='conditioning', name='products...
#!/usr/bin/env python # coding: utf-8 # ## Soal 1 # In[14]: nama = str(input("Masukan Nama : ")) Umur = int(input("Masukan umur : ")) # 17 tapi boong Tinggi = float(input("Masukan tinggi badan : ")) print("Nama saya " + nama + " , umur saya " + f'{Umur}' + " tahun, dan tinggi saya " + f'{Tinggi}' + " cm") # In...
from os.path import isfile, dirname, join, realpath from cached_property import cached_property from isabl_cli import AbstractApplication from isabl_cli import options from myapps.utils import get_docker_command from myapps.apps.merge.apps import Merge class Annot(AbstractApplication): NAME = "ANOT" VERSIO...
def Bs(arr,key): low = 0 high = len(arr)-1 while low <= high: mid = (low+high)//2 if arr[mid] == key: return "Element found at position : " +str(mid+1) elif arr[mid] < key: low = mid+1 else: high = mid-1 return "key not found" b = B...
# -*- coding: utf-8 -*- # @Author : William # @Project : TextGAN-william # @FileName : CoT_Medicator.py # @Time : Created at 2020/4/20 # @Blog : http://zhiweil.ml/ # @Description : # Copyrights (C) 2018. All Rights Reserved. import torch import torch.nn.functional as F from models.gen...
from django.urls import path from . import views urlpatterns = [ path('', views.SearchTimetable.as_view(), name="searchTimetable") ]
import logging import os from paths import KEYWORDS_PATH, CACHE_DIR logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(threadName)s:(%(name)s) [%(funcName)s()] %(message)s') logger = logging.getLogger(__name__) from twi_spider import TwiSpider if __name__ == '__main_...
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-08-24 17:12 from __future__ import unicode_literals import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('tracks', '0008_auto_20160824_1711'), ...
result = None A = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} result = set() temp = set() for x in A: temp.add(x) result.add(frozenset(temp)) print(result) assert frozenset((0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) in result
# class with __init__ class C1: def __init__(self): self.x = 1 c1 = C1() print(type(c1) == C1) print(c1.x) class C2: def __init__(self, x): self.x = x c2 = C2(4) print(type(c2) == C2) print(c2.x)
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for ged4py encodings handling.""" import io import logging import pytest from ged4py.parser import GedcomReader, CodecError def _check_log_rec(rec, level, msg, args): assert rec.levelno == level assert msg in rec.msg assert rec.args == args def t...
""" 줄을 바꿔 정수(integer) 2개를 입력받아 줄을 바꿔 출력해보자. """ num1 = input() num2 = input() print(num1) print(num2)
#! /usr/bin/python import sys import os from numpy import * #This script is to take the three matrices for the correlation calculation and convert them into 0/1 matrices. f=open('dihVal18.bin','w') d=open('dihVal18.new','r') for line in d: newline=[] s=line.split() for word in s: word=float(word) value=0 if ...
# В списке все элементы попарно различны. # Поменяйте местами минимальный и максимальный элемент этого списка numList = list(map(int, input().split())) max_i = numList.index(max(numList)) min_i = numList.index(min(numList)) numList[max_i], numList[min_i] = numList[min_i], numList[max_i] print(*numList)
def reversDigits(num): string = str(num) string = list(string) string.reverse() string = ','.join(string) return string if __name__ == "__main__": num = int(input("enter a number")) print("Reverse of no. is ", reversDigits(num))
""" Find all undefined reference targets and attempt to determine if they are code by emulation behaviorial analysis. (This module works best very late in the analysis passes) """ import envi import vivisect import vivisect.exc as v_exc from envi.archs.i386.opconst import * import vivisect.impemu.monitor as viv_imp_mo...
#!/usr/bin/env python """ Unit tests for python Enum class """ __author__ = 'VMware, Inc.' __copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved. -- VMware Confidential' # pylint: disable=line-too-long import logging import unittest from vmware.vapi.bindings.enum import Enum from vmware.vapi.bindings.ty...
#! /usr/bin/env python #coding=utf-8 import rospy from rb_msgAndSrv.srv import rb_ArrayAndBool, rb_ArrayAndBoolRequest, rb_ArrayAndBoolResponse rospy.init_node("cli_test") client = rospy.ServiceProxy("Rb_grepSetCommand", rb_ArrayAndBool) # a = rb_ArrayAndBool() # a.data = print(client.call([0, 2, 1, 0]))
# Generated by Django 2.2.5 on 2019-11-06 10:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('private_profiles', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='profile', name='bio', ...
class PlayerCaracter: membership = True def __init__(self, name, age): self.name = name self.age = age if ( PlayerCaracter.membership ): self.name = 'juan' def run(self): print( 'run' ) def shout(self): print(f'my name is {self.name}') player1 = PlayerCaracter( 'juan', 33 ) player2 = PlayerCaract...
# import libraries from bs4 import BeautifulSoup #import urllib.request from selenium import webdriver from selenium.webdriver.chrome.options import Options import csv import time import pandas as pd import numpy as np import matplotlib.pyplot as plt #from sklearn.model_selection import train_test_split #from sklearn.l...
import os import csv import cv2 import imutils import random import numpy as np from pprint import pprint from collections import Counter from PIL import Image as Img from PIL import ImageTk from random import randint from Tkinter import * import Tkinter,tkFileDialog, tkMessageBox meta_path = "./Tournament_Logs/Meta_In...
""" Handles the storage of Github information on a database """ import dbutils DATABASE_FILE = "github.sqlite" TAG_DDL = "CREATE TABLE release_tag " \ "(repository TEXT, name TEXT, zipball_url TEXT, tarball_url TEXT, commit_sha TEXT ," \ " commit_url TEXT, PRIMARY KEY (repository, name))" COMMIT_D...