text
stringlengths
38
1.54M
from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from .factory import PlayerFactory, TeamFactory from .models import PlayerModel, TeamModel class TestTeam(APITestCase): """ This class includes test cases for Team happy path. """ def setUp(self):...
# import all the required libraries # spacy for lemmatization import en_core_web_sm import numpy as np import pandas as pd nlp = en_core_web_sm.load() # plotting tool # import pyLDAvis # import pyLDAvis.gensim import nltk from nltk import word_tokenize import re from nltk.metrics import edit_distance from nltk.corp...
from redis import Redis, DataError from redis.client import Pipeline from redis.client import bool_ok from redis._compat import nativestr class TSInfo(object): rules = [] labels = [] sourceKey = None chunk_count = None memory_usage = None total_samples = None retention_msecs = None las...
from tree.tree_node import TreeNode def inorder_traversal(root): """ :type root: TreeNode :rtype: List[int] """ if root is None: return [] node_stack = [] done = False current = root result = [] while not done: if current is not None: node_stack....
import abc import uuid import base64 import datetime from dataclasses import dataclass from typing import Tuple, Any, List from server_protocol import SignupRequest class StorageLayerException(Exception): ... class StorageLayer(abc.ABC): @abc.abstractmethod def get_user_by_id( self, identifier: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 4 22:33:07 2018 @author: bruce """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 9 17:02:59 2018 @author: bruce """ import pandas as pd import numpy as np from scipy import fftpack from scipy import signal import matplot...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # Copyright © 2016 root <root@VM-17-202-debian> #create a list xs = [3, 1, 2] print xs, xs[2] print xs[-1] xs[2] = 'foo' print xs xs.append('bar') print xs print xs.pop(), xs nums = [0,1,2,3] squares = [] for x in nums: squares.append(x**2) print s...
import binascii ## Below function helps to convert a little endian hex string to decimal value def le_2_de(a): l='' k=0 for i in range(0,len(a)/2): k=len(a)-2*i l=l+a[k-2:k] l=int(l,16) return l ### Below function is to pull the hex value from hex data of image and print output def c...
#Changes: # OFFSET(B2,0,4) #To: # INDIRECT("'New Matrix'!$F$" & ROW($A2)) import string from itertools import combinations_with_replacement as cwr alphabet = string.ascii_lowercase length = 2 alpha1 = ["".join(letter) for letter in string.ascii_lowercase] alpha2 = ["".join(comb) for comb in cwr(alphabet, length)] ...
#!/usr/bin/env python3 import ruamel.yaml from ruamel.yaml.comments import (CommentedMap, CommentedSeq) import fileinput import os import sys from netaddr import IPNetwork # This version saves comments/edits in YAML files yaml = ruamel.yaml.YAML() yaml.indent(sequence=4, mapping=2, offset=2) # Input colte_vars = "/e...
import os import errno import uuid import settings from unicodedata import normalize import re from django.db.models import Q def create_obj2(klass_obj, params): return create_obj({}, klass_obj, params) def create_obj(id, klass_obj, params): obj = None if id: try: obj = klass_obj.obj...
from django.shortcuts import render from django.contrib.auth import get_user_model from rest_framework.generics import CreateAPIView from rest_framework.permissions import AllowAny from rest_framework.response import Response from rest_framework import status from .serializers import RegisterSerializer User = get_user...
from main_files.db.connect_db import CONNECTION cur = CONNECTION.cursor() query = """ UPDATE symptom_tag_relations SET symptom_id = %s, tag_id = %s WHERE symptom_tag_relation_id = %s """ def update_symptom_tag_relations(symptom_id=None, tag_id=None): cur.execute(query, [ symptom_id, ta...
# coding: utf-8 # In[ ]: from hdx.utilities.easy_logging import setup_logging from hdx.hdx_configuration import Configuration from hdx.data.dataset import Dataset import os import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import nltk import re # In[ ]: setup_logging()...
import sys import os cwd = os.getcwd() sys.path.append(cwd + os.sep + "..") from class_pixeltable import PixelTable import matplotlib.pyplot as plt import matplotlib.animation as animation import mpl_toolkits.mplot3d.axes3d as p3 from matplotlib._png import read_png from matplotlib.cbook import get_sample_data...
# Imports import models from flask import Blueprint, request, jsonify from playhouse.shortcuts import model_to_dict # ------------------------------------------------------------------------------------------------------ # Blueprints park = Blueprint('park', 'park', url_prefix="/api/v1") #...
from django.contrib import admin from censo.models import * admin.site.register(Encuestador) admin.site.register(Sector) admin.site.register(Colonia) admin.site.register(Parentesco) admin.site.register(Religion) admin.site.register(Sexo) admin.site.register(Calle) admin.site.register(Encuesta) admin.site.register(Fami...
__all__ = ["response", "repeat", "replay"] class EventHook: def __init__(self): self._handlers = [] def __iadd__(self, other): self._handlers.append(other) return self def __isub__(self, other): self._handlers.remove(other) return self def fire(self, **kwarg...
from contracts import contract __all__ = ['PlanningResult'] class PlanningResult(object): """ Results of planning. (more fields might be added in the future) """ @contract(success='bool', plan='None|seq(int)', status='None|str', extra='dict') def __init__(self, success, plan, status, extra={}): ...
from mrjob.job import MRJob from mrjob.step import MRStep from itertools import tee import re import sys WORD_RE = re.compile(r"[\w']+") class MRWordProbability(MRJob): def steps(self): return [ # Pull strings out of the csv MRStep(mapper=self.mapper_pull_c...
from BrickPi import * #import BrickPi.py file to use BrickPi operations import math import time BrickPiSetup() # setup the serial port for sudo su communication BrickPiSetupSensors() #Send the properties of sensors to BrickPi BrickPiUpdateValues() d=56 O=math.pi*d BrickPi.EncoderOffset[PORT_C] = BrickPi.Enc...
# Use este codigo como ponto de partida # Leitura de valores de entrada var = input("Arctic Monkeys") # Impressao de saidas: print(var) print(var)
from pyparsing import * unicode_char = Forward() unicode_letter = Forward() unicode_digit = Forward() letter = Forward() decimal_digit = Forward() octal_digit = Forward() hex_digit = Forward() identifier = Forward() int_lit = Forward() decimal_lit = Forward() octal_lit = Forward() hex_lit = Forward() float_lit = Forwa...
import numpy as np from numpy.linalg import matrix_power A = np.array([ [-1, 4, 8], [-9, 1, 2] ]) B = np.array([ [5, 8], [0, -6], [5, 6] ]) C = np.array([ [-4, 1], [6, 5] ]) D = np.array([ [-6, 3, 1], [8, 9, -2], [6, -1, 5] ]) print('a') print((A @ B).T) print('b') print((B @ C)...
from django.urls import path, re_path from django.conf.urls import url from . import views urlpatterns = [ url('menu/wrapper.html', views.wrapper), url('menu/main.html',views.main), url('menu/condition.html', views.condition), url('menu/content.html', views.content), url('menu/', views.menu), ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Feb 7 09:21:48 2017 @author: obarquero """ from __future__ import division import numpy as np import zlib from backports import lzma import bz2 class NCD(object): def __init__(self,x=[],y=[],compressor = []): self.x = x se...
import time def ConsolePrint(string, type):#type "c" client, "s" server clock = time.strftime('%X') if type == "c": print(clock, " [CLIENT]: ", string) elif type == "s": print(clock, " [SERVER]: ", string)
from __future__ import division import time from smbus import SMBus import Adafruit_PCA9685 import subprocess import math import numpy as np from ast import literal_eval PI = 3.14 #Global Variables pwm2 = Adafruit_PCA9685.PCA9685(address=0x41, busnum=1) pwm2.set_pwm_freq(50) bus = SMBus(1) FL_sensor = 0 FR_sensor = ...
#raw_input ka use kar ke 3 alag variables mein 3 integers ka input lein. Input lene ke baad inn 3 mein se sabse bade number ko print karo first = raw_input("enter a number")# we took a input from a user in a string form First = int(first)#we converted string into integer second = raw_input("enter another number")# we ...
from services.views.spi import SpiApi from authentications.utils import get_correlation_id_from_username from django.contrib import messages from django.views.generic.base import TemplateView from django.shortcuts import redirect import logging from web_admin import setup_logger,api_settings logger = logging.getLog...
from django.db import models # Create your models here. class TestManager(models.Manager): def create_tweet(self,d): tweet = self.create(**d) return tweet class TestModel(models.Model): objects = TestManager() updated = models.DateTimeField(auto_now=True) created = models.DateTimeFie...
#!/usr/bin/env python # Exercise 4 # (1) Modify reverse_lookup_old so that it builds and returns a list of all # keys that map to v, or an empty list if there are none. # (2) Paste in your completed functions from HW08_ex_11_02.py # (3) Do not edit what is in main(). It should print what is returned, a list # of th...
# -*- coding: utf-8 -*- """ (Description) Created on Oct 16, 2014 """ import json from os.path import dirname, abspath import sys basePath = dirname(abspath(__file__)) + '/../../' sys.path.insert(0, '../../') from ce1sus.helpers.common.config import Configuration from ce1sus.controllers.admin.attributedefinitions ...
import csv import io import os import tkinter as tk import xml.etree.cElementTree as xmlET from tkinter import filedialog import tokenizeJudgements class JudgementEntity: def __init__(self, id, text, label=""): self._id = id self._text = text self._label = label def runScript(): ...
""" SWARM Trough detection: - 3 point median filter - cut into 45-75 MLAT segments - background = sliding window of 480 points - check detrended logarithmic density to see if it has negative peak that both corresponds to the local Ne minimum within "the window" and lower than a threshold of -0.3...
#!/usr/bin/env python # -*- coding: utf-8 -*- import requests import json import re import datetime import uuid import logging class TelegramBot: # telegram bot settings last_update_id = 0 start_message = '{} Я могу сообщать текущую температуру в Поселке Программистов в ответ на любое сообщен...
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # 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,...
class cbase(): def __init__(self) : self.items = [] self.indentLvl = 0 self.indentAmt = 2 def generateOrUse(self, item): if hasattr(item, "generate"): item.indentLvl = self.indentLvl + 1 return item.generate() else: return self.getInd...
from __future__ import absolute_import, division, print_function import sys import os sys.path.append(os.environ['PERF_EXEC_PATH'] + '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') expected_command = sys.argv[1] def process_event(params): if params["comm"] != expected_command: return ...
import math import numpy as np import random # * parameters k_fold = 5 random.seed(291) # * import/read raw dataset input_filename = "admission_predict.csv" with open(input_filename, "r") as f: dataset = f.readlines() # * cleanse dataset (i.e. remove header) dataset = dataset[1:] # * shuffle relavant inputs ran...
#Tutor assistant database file, by Cyani #This is the main program. All other programs written are run from here #Thank you to Python Central for teaching me how to use basic database operations in python using sqlite3 #Credit is also given in each file where due #Throught the program, procedures beggining with "a" ar...
import os import time import datetime import osmnx as ox import networkx as nx import matplotlib.cm as cm import matplotlib.pyplot as plt import matplotlib.colors as mpcol import matplotlib matplotlib.use('Agg') ox.config(data_folder='../Data', logs_folder='../logs', imgs_folder='../imgs', cache_folder='../...
# -*- coding: utf-8 -*- # # Author: Alberto Planas <aplanas@suse.com> # # Copyright 2019 SUSE LLC. # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The A...
import pygame import math import random from params import * from Setup import * from Effect import * import GameObject as go def addVector(vector1 , vector2): x = math.sin(vector1.angle)*vector1.length + math.sin(vector2.angle)*vector2.length y = math.cos(vector1.angle) * vector1.length + math.cos(...
import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT = os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__)))) # PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # SECURITY WA...
# Write for loops to produce the following output: # 1 # 22 # 333 # 4444 # 55555 # 666666 # 7777777 number_one = 1 height_of_triangle = int(input("Enter height of triangle: ")) print(number_one) for i in range(height_of_triangle - 1): number_one = number_one + 1 for j in range(number_one): print(number...
# Generated by Django 2.1.1 on 2018-11-19 18:03 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
# Generated by Django 3.1.1 on 2020-11-13 21:44 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Investimento', fields=[ ('id', models.AutoF...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 28 14:36:29 2018 @author: lee """ import os from PIL import Image from collections import Counter import re import pandas as pd file_list = [] path_list = os.listdir('./') ##筛选都有的icon ''' for path in path_list: if '_ic_' in path: print...
from ckeditor.widgets import CKEditorWidget from django import forms from .models import Requirement class RequirementForm(forms.ModelForm): long_description = forms.CharField(widget=CKEditorWidget()) short_description = forms.CharField(widget=forms.Textarea) class Meta: model = Requirement ...
# -*- coding: utf-8 -*- import json # sys.path.append ("tiny_func") from tiny_func import get_counts2 path = "pydata-book-2nd-edition/datasets/bitly_usagov/example.txt" records = [json.loads(line) for line in open(path,encoding = "utf-8")] time_zones = [rec["tz"] for rec in records if "tz" in rec] tz_counts = get_cou...
z=int(input()) xyz=list(map(str,input().split())) xyz=sorted(xyz,reverse=True) print(("".join(xyz)))
#!/usr/bin/python import os.path from libs.ioScore import * from libs.ioPDBbind import * from libs.constConf import * scoreListGOLD = ['plp', 'goldscore', 'chemscore', 'asp'] scoreListXSCORE = ['HPScore', 'HMScore', 'HSScore'] scoreListGLIDE = ['SP', 'XP'] scoreListPARA = ['DrugScore', 'pScore', 'PMF'] CASFyea...
#! /usr/bin/python import sys import os from setuptools import setup, Extension version = "0.1.4" setup( name="mongorm", version=version, packages=["mongorm"], author="Simversity Inc.", author_email="dev@simversity.com", url="http://simversity.github.io/mongorm", license="http://www.apach...
import time import math import statistics def selectionsort(L): start = time.time() for i in range(len(L)): for j in range(i+1, len(L)): while L[j] < L[i]: L[i],L[j] = L[j],L[i] end = time.time() return L, end - start def sumksquare(k): start = ti...
# Игра крестики - нолики, Автор: Панков Ю. А. # _*_ coding: utf-8 _*_ import random def draw_field(field): """ Функция отрисовки поля """ print("-------------") for i in range(3): # после первой отрисвки для красоты можно не отрисовывать цифры print("|", field[0+i*3], "|", fiel...
#!/usr/bin/python3 print("content-type: text/html") print() import subprocess as sp import cgi form = cgi.FieldStorage() osimage = form.getvalue("x") cmd = "sudo docker history {}".format(osimage) output = sp.getstatusoutput(cmd) print(output) ~ ~
class WhoIsError(Exception): pass class QueryError(WhoIsError): pass class NotFoundError(WhoIsError): pass
''' Given a lowercase string that has alphabetic characters only and no spaces, return the highest value of consonant substrings. Consonants are any letters of the alphabet except "aeiou". We shall assign the following values: a = 1, b = 2, c = 3, .... z = 26. For example, for the word "zodiacs", let's cross out the ...
#In this assignment you will read through and parse a file with text and numbers. You will extract all the numbers in the file and compute the sum of the numbers. """ Data Files We provide two files for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual data ...
import sys import vptree from scipy import spatial import numpy as np if __name__ == '__main__': X = np.random.randn(10, 10) # knn = spatial.cKDTree(X, leafsize=10) vptree = vptree.vptree(sparse = True) X = np.asarray([[[1,2], [2,5], [3,4]], [[1,5],[3,1],[5,1]], [[1,0.1],[2,5],[10,...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 12 10:53:51 2020 @author: scro3517 """ import numpy as np import os import pickle from tqdm import tqdm import pandas as pd from itertools import compress #%% def load_paths(basepath): """ File Names to Load """ files = os.listdir(os.path....
__author__ = 'Antoine' from naturalLanguagePython.countryDomain.countryRepository import CountryRepository from naturalLanguagePython.countryDomain.country import Country class CountryRepositoryDB(CountryRepository): def __init__(self): self.countryList = [] def addCountry(self, country): se...
# Configuration test file from bibliopixel.led import* #~ from bibliopixel.animation import MatrixCalibrationTest from bibliopixel.drivers.APA102 import* import bibliopixel.colors as colors #~ from LEDfuncs import* #~ from time import sleep #~ from animation import* #~ import numpy # Global Vars NUM = 8*8 rainbow = [...
import util def pack((W,H), unpacked, packed, active, area, on_update): # Base Cases: if not unpacked: on_update(active, packed, None, None, unpacked, "Nothing left to pack. Success.") return True, packed if area > W*H: on_update(active, packed, None, None, unpacked, "... no ro...
import configparser #处理ini文件 iniFileName = 'iniFileName.ini' cred = 0 config = configparser.ConfigParser() config.read(iniFileName, encoding='utf-8') sectionName = 'config' list = config.sections() # 获取到配置文件中所有分组名称 if sectionName in list: # 如果分组存在 cred = config.getfloat(sectionName, "Credits") print(cred)
#!/usr/bin/env python import os,sys import subprocess from optparse import OptionParser SYSTEM_MOUNTPOINTS = set(['/proc', '/sys']) def main(): p = OptionParser(usage="%prog [OPTIONS] cmd") p.add_option('-b', '--base') p.add_option('-s', '--shadow', action='append', default=[], dest='shadow_dirs') p.add_option('-...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 17 10:10:23 2021 @author: tai """ import numpy as np import cv2 cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() width = int(cap.get(3)) height = int(cap.get(4)) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) ...
import os import logging from collections import defaultdict import pandas as pd from fol.foq_v2 import (concate_n_chains, copy_query, negation_sink, binary_formula_iterator, concate_iu_chains, parse_formula, ...
# -*- coding: utf-8 -*- # @Time : 2019/3/18 14:30 # @Author : from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class Profile(AbstractUser): ''' 用户 ''' name = models.CharField(max_length=50, null=True, blank=True, verbose_name='姓名', help_te...
""" @author: Badita Marin-Georgian @email: geo.badita@gmail.com @date: 22.03.2020 00:21 """ import pytest from dronem_gym_env.envs import DronemEnv from env_interpretation import Meeting @pytest.fixture def env4_robots(): """ Returns the environment, alongside its pair mapping :return: ...
# -*- coding: utf-8 -*- """ Created on Thu Aug 6 22:16:49 2020 @author: Caven """ class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: dic = {} for cp in cpdomains: visit, domain = cp.split(' ',2) domainSplit = domain.split('.') n = len...
# -*- coding: utf-8 -*- """ Created on Tue Jul 21 15:51:25 2020 @author: BreezeCat """ import math as m import matplotlib.pyplot as plt import copy import json class State(): def __init__(self, Px, Py, Pth, V, W, r): self.Px = Px self.Py = Py self.Pth = Pth self.V = V self....
"""Test IOLoop watcher interface.""" from julythontweets.watcher import Watcher from tornado.ioloop import IOLoop from unittest2 import TestCase class TestWatcher(TestCase): def test_base_watcher(self): """Test the watcher interface.""" ioloop = IOLoop() def callback(): pass...
import os import logging import ckan.plugins as p from ckan.model.types import make_uuid from ckan.lib.celery_app import celery log = logging.getLogger(__name__) def create_archiver_resource_task(resource, queue): from pylons import config if p.toolkit.check_ckan_version(max_version='2.2.99'): # ear...
sal = float(input('Digite o Salario do Funcionario: ')) if sal > 1250: print('Com um aumento ele passara a receber R${:.2f}'.format(sal + (sal / 100 * 10))) else: print('Com um aumneto ele passara a receber R${:.2f}'.format(sal + (sal / 100 * 15)))
def addlist(): fruits = ["Apple", "Orange", "Mango"] fruit = input("Enter the fruit name:\t") fruits.append(fruit) print("You have succesfully added \"{}\" into the list".format(fruit)) print(fruits) addlist()
#!/usr/bin/python2.7 import cv capture = cv.CaptureFromCAM(0) hc_src = '/home/ko/Downloads/Hand.Cascade.1.xml' hc_src = '/home/ko/Downloads/haarcascade_frontalface_default.xml' hc = cv.Load(hc_src) storage = cv.CreateMemStorage(0) while True: frame = cv.QueryFrame(capture) hands = cv.HaarDetectObjects(fram...
#!/usr/bin/env python #--coding:utf-8-*- ''' 创建人: Javen 创建时间:2017/2/9 ''' import sys from Models.DbTable.Abstract import Model_DbTable_Abstract class Model_Mapper_Abstract(object): def __init__(self): self.dbTable = Model_DbTable_Abstract() self.mapper = self.dbTable.mapper self.amazon = se...
import os import xml.etree.ElementTree as ET from rogue_sky import darksky DARKSKY_API_KEY = os.environ["DARKSKY_SECRET_KEY"] def test_ping(backend_api_client): response = backend_api_client.get("/api/health") assert response.status_code == 200 assert response.get_json() == {"status": "ok"} def test_g...
import matplotlib.pyplot as plt class Plots: def plt_ini(self, figw=16.0, figh=6.0, rows=1, cols=1): fig, axes = plt.subplots(cols, rows, sharex=True, sharey=True, figsize=(figw, figh)) plt.subplots_adjust(left=1 / figw, right=1 - 1 / figw, bottom=1 / figh, top=1 -...
# This file is part of HappySchool. # # HappySchool is the legal property of its developers, whose names # can be found in the AUTHORS file distributed with this source # distribution. # # HappySchool is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License a...
#!/usr/bin/env python #============================================================================= # # Copyright (c) 2018 Qualcomm Technologies, Inc. # All Rights Reserved. # Confidential and Proprietary - Qualcomm Technologies, Inc. # #============================================================================= ...
class Solution(object): def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ # import heapq # nums = list(set(nums)) # if len(nums) < 3: # return max(nums) # num_heap = nums[:3] # heapq.heapify(num_heap) # ...
# -*- coding: utf-8 -*- """ 聚类离散化,最后结果的格式为: 1 2 3 4 A 0 0.178698 0.257724 0.351843 An 240 356.000000 281.000000 53.000000 ... 即(0, 0.178698]有240个,(0.178698, 0.257724]有356个,依此类推其他项。 """ import pandas as pd from sklearn.cluster import KMeans dataFile = './data/data.x...
#!/user/bin/env python3 print("Hello, " + input("Please enter your name: ")+"!", " Happy " + input("What day of the week is it? ") + "!") # using .format print("Hello, {}! Happy {}!".format(input("What's your name? "), input("What day is it? "))) # using f string name = input("What's your name? ") day = input("Wha...
# -*- coding: utf-8 -*- # Generated by Django 1.11.17 on 2020-06-20 09:51 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('check', '0004_postmodel_hidung_tersumbat'), ] operations = [ migrations.Ad...
''' example of simple transformation for z-shifted catmaid data. Expects c2z.py json in working directory ''' import json dumpfn = './20160503_export_FromDB.json' # TODO maybe make this date based? outfn = './20160503_newnodedump.txt' c2zfile = './c2z.json' with open(c2zfile, 'r') as j: c2z = json.l...
# Generated by Django 2.2 on 2021-06-02 23:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0012_auto_20210602_2001'), ] operations = [ migrations.AlterField( model_name='categoria', name='slug', ...
import random from pico2d import * class Target: image = None LEFT_RUN, RIGHT_RUN, LEFT_STAND, RIGHT_STAND = 0, 1, 2, 3 def __init__(self): self.x, self.y = 0, 0 #선택대상의 좌표 self.select = None #선택 대상 if Target.image == None: Target.image = load_image('target.png') ...
# -*- coding: utf-8 -*- # CONSTANTS - FOR MODEL-JS import sys reload(sys) sys.setdefaultencoding('utf-8') sys.path.append('../') from codegen_consts import * UNCAPITALISED_MODEL_NAME_MARKER = "{{uncapitalised_model_name}}" SNAKE_CASE_MODEL_NAME_MARKER = "{{snake_case_model_name}}" MODEL_DISPLAY_NAME_MARKER = "{{model_...
alumnos = ("Alberto", "Juan", "Daniel") notas_de_Alberto = [] # para Alberto while True: nota = input(f"ingrese la primera nota de {alumnos [0]} : ") notas_de_Alberto.append(nota) nota = input(f"ingrese la segunda nota de {alumnos [0]} : ") notas_de_Alberto.append(nota) nota = input(...
def main(): array=input() array=list(map(int,array.split())) counter={} for each in array: counter[each]=array.count(each) # print(max(counter,key=counter.get)) return len(array)-counter[max(counter,key=counter.get)] def custom(): array=input() array=list(map(int,array.split())...
from collections import deque import numpy as np class FrameStack(): def __init__(self, initial_frame, stack_size=4, preprocess_fn=None): # Setup initial state self.frame_stack = deque(maxlen=stack_size) initial_frame = preprocess_fn(initial_frame) if preprocess_fn else initial_frame ...
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import Client import unittest import logging import json logging.basicConfig(level=logging.INFO, format="%(message)s") class GetLtlTest(unittest.TestCase): def setUp(self): self.client = Client() ...
''' Sawyer Coleman US07 Functions File SSW_555_Agile_Methods BHS_Project_SSW_555 Homework04 ''' from datetime import datetime import calendar '''Calculates Age''' months = {"JAN": 1,"FEB": 2 ,"MAR": 3,"APR": 4,"MAY": 5,"JUN": 6,"JUL": 7,"AUG":8,"SEP": 9,"OCT": 10,"NOV": 11,"DEC": 12 } #Calculate...
import time from src.plots.bar import AnimatePlot from src.generate_data import generate generate(kind='list', size = 20) f = open('input.txt', 'r') inp = f.read() array = list(map(int, inp.split(','))) plot = AnimatePlot("insertion_sort_Sort") plot.update(array, 0, 0) _len = len(array) plot._len = _l...
""" Description: Simultaneous Perturbation Stochastic Approximation Example Use: """ from tqdm import tqdm import torch from torch import nn from ._fgsm import FGSM, FGM from ._utils import clip __all__ = ["SPSA"] def SPSA(net, x, y_true, data_params, attack_params, loss_function="cross_entropy", verbose=False,...
# Generated by Django 3.0.4 on 2020-03-21 17:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('rentals', '0002_games'), ] operations = [ migrations.AddField( model_name='games', ...
import itertools def factorial(n): if n< 2: return 1 return n * factorial(n-1) def build_count(x, S): ans = 1 for v in S: if len(x[v])<3: return 0 ans *= len(x[v])-2 return ans def count_comp(g,S): unseen = set(g.edges) components = 0 while unseen: components +=1 used_vertices = set() e = unse...