text stringlengths 8 6.05M |
|---|
# 3. Use `functools.wraps` to preserve the function attributes
# including the docstring that you wrote.
# 1. Write a function decorator that can be used to measure
# the run time of a functions. Use `timeit.default_timer` to get time stamps.
import functools
from timeit import default_timer as timer
def runtime1(fu... |
# Generated by Django 3.1.1 on 2020-09-15 06:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attend', '0005_face_emp_id'),
]
operations = [
migrations.CreateModel(
name='gender',
fields=[
('id'... |
#Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra “A”, em que posição ela aparece a primeira vez e em que posição ela aparece a última vez.
frase = str(input('Digite uma fase: ')).upper().strip()
print('A letra "A" aparece {} vezes na frase'.format(frase.count('A')))
print('A pri... |
# Generated by Django 2.1.5 on 2019-01-29 21:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('telecomNews', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='articles',
name='image',
... |
"""
- numpy is not used here because it's not necessary and
it's simpler using list for this question
"""
import matplotlib.pyplot as plt
class population_growth(object):
# alpha_fun is a function that gives the growth of the population
# according to the size of the current population
# by default... |
#导入模块
from flask_sqlalchemy import SQLAlchemy
import pymysql
#创建flask对象
app = Flask(__name__)
#配置flask配置对象中键:SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://username:password@hostname/database"
#配置flask配置对象中键:SQLALCHEMY_COMMIT_TEARDOWN,设置为True,应用会自动在每次请求结束后提交数据库中变动
app.config['SQLA... |
import numpy as np
import cv2
CHOOSEM_CONTOURS_NUM = 400
CARDS_ALPHA = 0.2
def preprocess_threshhold_background_noise(img, thresh_size):
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
_, saturation, _ = cv2.split(hsv)
lap = cv2.Laplacian(
saturation, cv2.CV_8U, saturation, ksize=3)
kernel = cv2.g... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from kouzi_crawler.items import KouziCrawlerItem
class LelejiaSpider(CrawlSpider):
name = 'lelejia'
allowed_domains = ['lelejia.top']
start_urls = ['http://lelejia.top/']
... |
# -*_ coding: utf-8 -*-
import os
import glob
print(os.getcwd())
print(os.path)
pathname = '/Users/pilgrim/diveintopython3/examples/humansize.py'
(dirname,filename) = os.path.split(pathname)
print(dirname)
print(filename)
metadata = os.stat('test2.py')
print(metadata.st_mtime)
import time
print(time... |
"""A captioner implementation that batch-processes new images.
In the future, this could be switched out with a streaming implementation
that doesn't require the image recognition framework to boot up each time
for potentially sizable speed increases."""
import glob
import os
import re
import requests
import shutil
im... |
#!/usr/bin/python3.4
# -*-coding:Utf-8
maliste = [1, 2, 3, 4, 5]
i = 0
maliste.extend("END")
maliste.insert(2, "2.5")
while i < len(maliste):
print(maliste[i])
i += 1
for elt in maliste:
print(elt)
i = 0
for i, elt in enumerate(maliste):
print("A l'indice {} se trouve {}".format(i, elt))
|
# tarot dot py is a program by socrates mcbadger (beinnisbog.tumblr.com)
# it is liscensed under the apache license 2.0
import random
major_arcana = ['0: the fool', 'I: the magician', 'II: the high preistess',
'III: the empress', 'IV: the emperor', 'V: the hierophant',
'VI: the lovers'... |
# Generated by Django 3.0.3 on 2020-03-31 13:22
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='url',
old_name='shortened_url',
... |
# helper methods for the users app
def users_session_data(request):
responseData = {
'user': {
'id': request.user.id,
'username': request.user.username,
'sessionKey': request.session.session_key,
}
}
return responseData
|
# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from typing import Sequence
from pants.option.option_types import StrListOption
from pants.option.subsystem import Subsystem
from pants.util.strutil im... |
from datetime import timedelta, datetime
from typing import Optional
from jose import jwt
# Generated using: openssl rand -hex 32
SECRET_KEY = 'b0b8c74b7ef83e39fc9395050f68583fb8b6c643fa082d475518fe436ac6ddb5'
ALGORITHM = 'HS256'
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 1 Week
class JwtService:
"""Service... |
from django.db import models
import datetime
# Create your models here.
class Notice(models.Model):
notice = models.CharField(max_length=1000)
images = models.FileField(upload_to='notice/images/', default='', blank=True, null=True)
pdf = models.FileField(upload_to='notice/files/',default='', blank=True, nu... |
from django.contrib import admin
from principal.models import Actor, Pelicula
# Register your models here.
@admin.register(Actor)
class ActorAdmin(admin.ModelAdmin):
pass
@admin.register(Pelicula)
class PeliculaAdmin(admin.ModelAdmin):
pass
|
import numpy as np
from PIL import Image
import torch
import os
import torch.utils.data as data
from glob import glob
from .common import BaseDataset
class davis2017(BaseDataset):
def __init__(self, base_dir, split, transforms=None, to_tensor=None):
super(davis2017, self).__init__(base_dir)
self.s... |
from tkinter import *
from Connect import *
import sqlite3
import LoginPage
from tkinter.messagebox import *
class Register(object):
def __init__(self, master=None):
self.root = master
self.root.geometry('400x350')
self.root.resizable(width=False, height=False)
self.Name = StringVar... |
from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APIClient
import factory
from .models import TodoTask
class TodoTaskFactory(factory.django.DjangoModelFactory):
class Meta:
model = TodoTask
title = factory.Faker('text')
class TodoTaskTest(TestCase):
... |
"""
Example: /home/mcbs913_2018/shared/homoeologs_assembly/experiments_lambda/diploid/alf/div_05pct/illumina$ ls ref_contig_??.vcf | python3 /home/mcbs913_2018/shared/homoeologs_assembly/homoeolog_assembly/run_compare_vcf_on_contigs.py -A ../homolog5-1.vcf -a ../homolog5-1prime.vcf -B ../homolog5-2.vcf -b ../homolog5-2... |
#!/user/bin/python
import argparse
import collections
import logging
import os
import random
import sys
logging.getLogger("scapy").setLevel(1)
from scapy.all import *
parser = argparse.ArgumentParser(description="Test packet generator")
parser.add_argument('--out-dir', help="Output path", type=str, action='store', ... |
import unittest
from katas.kyu_7.highest_and_lowest import high_and_low
class HighAndLowTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(high_and_low('1 2 3 4 5'), '5 1')
def test_equal_2(self):
self.assertEqual(high_and_low('1 2 -3 4 5'), '5 -3')
def test_equal_3(s... |
def selectionsort (list1):
temp = 0
for i in range (0,len(list1)-1):
max_possible = i
for j in range (i,len(list1)):
if list1[j] > list1[max_possible]:
temp = list1[max_possible]
list1[max_possible] = list1[j]
list1[j] = temp
... |
from flask import Flask
from extensions import *
from config import DevelopmentConfig, STATIC_FOLDER
from models import *
from commands import test
from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, create_database
def create_app(config=DevelopmentConfig):
app = Flask(__name__, st... |
#_*_coding:utf-8 _*_
#用二分法求平方根
def sqrt_dichotomy(x, max, min=0):
print x, min, max
mid = (min + max)/2.0
print mid
if (mid * mid) - x > 0.0001:
max = mid
sqrt_dichotomy(x, max, min)
if (mid * mid) - x < -0.0001:
min = mid
sqrt_dichotomy(x, max, min)
else:
return mid
if __name__ == '__main__':
x = 10... |
from django import forms
from .models import Bank, Category, Transaction, Budget, BudgetCategory
import datetime
class BankForm(forms.ModelForm):
class Meta:
model = Bank
fields = ('starting_amount', 'name')
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fiel... |
from django.urls import path
from currency.views import currency
app_name = 'currency'
urlpatterns = [
path('', currency, name='currency'),
] |
import sys
import os
from os.path import isfile, join
import csv
import pandas as pd
import numpy as np
from scipy import stats
from collections import defaultdict
class MinMaxNormalise:
def __init__(self):
self.global_values = defaultdict()
def set_local_norms(self, csvs):
with open('mmx_loc... |
from django.forms import ModelForm
from django.core.exceptions import ValidationError
from school_list.models import Student,Teacher
class StudentForm(ModelForm):
class Meta:
model= Student
fields= ['s_name', 's_class', 's_dob', 's_address', 's_phonenum', 's_email']
class TeacherForm(ModelForm):
... |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
'''
author: Zitian(Daniel) Tong
date: 17:43 2019-05-25 2019
editor: PyCharm
email: danieltongubc@gmail.com
'''
from flask import Blueprint, render_template, request, url_for, redirect, session
from models.user import User, UserError
user_blueprint = Blueprint('users', __name__)
@user_blueprint... |
#! /usr/bin/env python
"""
Normalizes a vidoe by dividing against it's background.
See: BackgroundExtractor.py to get the background of a video.
USING:
As a command line utility:
$ Normalizer.py input_video input_image output_video
As a module:
from Normalizer import Normalizer
... |
# Generated by Django 3.2.6 on 2021-08-02 12:25
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
('social', '0003_comment'),
]
operations = [
migra... |
import logging
import time
import os.path
from numpy.random import RandomState
import lasagne
from lasagne.updates import adam
from lasagne.objectives import categorical_crossentropy
from lasagne.nonlinearities import elu,softmax,identity
from hyperoptim.parse import cartesian_dict_of_lists_product,\
product_of_lis... |
import warnings
from typing import Dict, Tuple, Union
import numpy as np
from phiml.math import DimFilter
from phi import math
from ._geom import Geometry, _keep_vector
from phiml.math import wrap, INF, Shape, channel, spatial, copy_with, Tensor
from phiml.math._shape import parse_dim_order
from phiml.math.magic impo... |
import numpy as np
class Neural_Network(object):
def __init__(self, architecture, error, indepdata, depdata):
self.index = indepdata.index.values
self.indepData = np.mat(np.atleast_2d(indepdata))
self.depData = np.mat(np.atleast_2d(depdata))
self.error = error[0]
... |
def reverse_string(string):
string = str()
if string == string[::-1]:
return "true"
elif string == "":
return 'None'
else:
return string[::-1]
|
from django.urls import path, include
from .views import (
ProductSearchListView,
ProductDetailView,
ProductListView,
product_by_timestamp,
)
app_name = 'products'
prod_class_patterns = ([
path('', ProductListView.as_view(), name='all'),
path('<sex>/', ProductListView.as_view(), name='sex'),
... |
# use dictionary to define graph structure
graph = {
'S' : ['A', 'D'],
'A' : ['D', 'B'],
'B' : ['C', 'E'],
'C' : [],
'D' : ['E'],
'E': ['B', 'F'],
'F': ['G'],
'G': []
}
visited = []
queue = []
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while q... |
d = float(input("enter Đường Kính "))
s = d*3.14
print("Area of Circle is",s,"m2")
|
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.db.models import Q, Avg
from django.http import HttpResponse, HttpResponseRedirect
fro... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
from torch.autograd import Variable as Var
from torch.optim import Adam
from torch.utils.data import DataLoader, TensorDataset
from models.attention import RawEmbeddingLayer
from utils import *
import numpy as np
# Run on gpu is present
... |
from selenium import webdriver #connect python with webbrowser-chrome
from selenium.webdriver.common.keys import Keys
import pyautogui as pag
def main():
url = "http://linkedin.com/" #url of LinkedIn
network_url = "http://linkedin.com/mynetwork/" # url of LinkedIn network page
driver = webdriver.Chrome('... |
import os
from spotibot.core.objects import \
Music
from spotibot.mongo.utils.Handlers import \
is_jsonable
def test_instantiation_serialization(result: dict):
"""Tests the instantiation of SpotiBot objects from raw API responses
and their conversion to byte-code based on the object's p... |
import socket, time, struct, binascii, mutex
import threading
import zmq
import numpy, scipy
CHANNEL_DEPTH = 128
UDP_PAYLOAD_SIZE = 818 #Derived from wireshark.
UDP_IP="" #This means all interfaces?
UDP_PORT=8899
#sock.setblocking(0)
class UDPThread(threading.Thread):
def __init__(self):
super(UDPThread,s... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
class Config(object):
def __init__(self, config_dict):
self.num_folds = int(config_dict["num_folds"])
self.fnc_root = config_dict["fnc_root"]
self.fnc_out_csv = config_dict["fnc_out_csv"]
self.fnc_sts_csv = config_dict["fnc_sts_csv"]
self.re17_root = config_dict["re17_root"]
self.re17_out_csv = config_dict... |
cpar = 0
cneg = 0
cpos = 0
for x in range(0, 5):
v = float(input())
if v > 0:
cpos += 1
elif v < 0:
cneg +=1
if v % 2 == 0:
cpar += 1
print('{} valor(es) par(es)\n{} valor(es) impar(es)\n{} valor(es) positivo(s)\n{} valor(es) negativo(s)'.format(cpar, (5 - cpar), cpos, cneg)) |
from PIL import Image
import numpy as np
def save_image(X_final, name, nb_colors):
im = Image.fromarray((X_final * 255).astype(np.uint8))
name = name.split(".")[0]
file_name = name + "_" + str(nb_colors) + ".jpeg"
im.save(file_name)
return file_name
def usage():
print("Usage :\npython main.py... |
import pytest
from django.contrib.auth.models import User
from django.urls import *
from Firma import settings
@pytest.mark.django_db
def test_user_create():
User.objects.create_user('kulpinskid', 'kulpinskid@gmail.com', 'dawid')
assert User.objects.count() == 1
@pytest.mark.django_db
def test_view... |
a, b = map(int, input().split())
result = [0, 0, 0]
for i in range(1, 7):
if abs(i - a) < abs(i - b):
result[0] += 1
elif abs(i - a) > abs(i - b):
result[-1] += 1
else:
result[1] += 1
print(*result)
|
# set provides: difference, intersection, union
print("SET EXAMPLES DIFFERENCE")
setExample = set("some set values")
print(setExample)
A = {10, 20, 30, 40, 80}
B = {100, 30, 80, 40, 60}
print("Set difference method")
print(A.difference(B))
print(B.difference(A))
print()
print("Minus operator")
print(A - B)
print(B... |
from django.shortcuts import render
from .models import Game
# Create your views here.
def main_page(request):
Games = Game.objects.filter(Popular=True)
return render(request, 'main.html', {'Games': Games})
def games(request):
Games = Game.objects.all()
return render(request, 'games.html', {'Games... |
from copy import deepcopy
class ConfigBuilder:
def __init__(self):
self._base_config = {}
self._matcher = {'KDTreeMatcher': {'knn': 1}}
self._inspector = 'NullInspector'
self._reading_dp_filter = []
self._reference_dp_filter = []
self._outlier_filters = []
... |
a = float(input('Please type the first line'))
b = float(input('Please type the second line'))
c = float(input('Please type the third line'))
if a < b + c and b < a + c and c < b + a:
print('\033[1;31mWith these lines we have a triangle')
else:
print('\033[1;35m not a triangle')
|
import cgi
import socket
import subprocess
import smtplib
import time
import urllib
import logging
import entity
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class UpdateTest(webapp.Requ... |
import os
import time
from SaveLoad import Patient,Doctor,Booking
def child(t,d_id):
time.sleep(t)
Booking.del_from_db_by_userid(d_id)
print(d_id+" doctor appointment info deleted from Booking table")
os._exit(0)
def parent(d_id):#Parameter Time Period and Discount Price
while True:
print(d_id)... |
#!/usr/bin/env python
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
#
# # Authors informations
#
# @author: HUC Stéphane
# @email: <devs@stephane-huc.net>
# @url: http://stephane-huc.net
#
# @license : BSD "Simplified" 2 clauses
#
''' Listener '''
import gobject
class Listener(gobject.... |
"""add table articles tags
Revision ID: c551860ba533
Revises: 05e65bf85f23
Create Date: 2019-12-13 15:00:48.298143
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c551860ba533'
down_revision = '05e65bf85f23'
branch_labels = None
depends_on = None
def upgrade... |
def planet_mass(gravity, radius):
mass = (gravity*radius**2) / (6.67*10**-11)
return mass
def planet_vol(radius):
vol = (4*3.142*radius**2)/3
return vol |
import re
import os
from os import popen, path
from sys import stderr
import psutil
from sv2.helpers import run_checkers
summary = "Check ssh configuration"
report = None
algorithm_blacklist = """
ecdh-sha2-nistp256 weak eliptic curves
ecdh-sha2-nistp384 weak eliptic curves
ecdh-sha2-nistp521 weak eliptic curves... |
# MAIN GOAL
#
# Create a program that allows the user to input the sides of any triangle, and then return whether the triangle is a Pythagorean Triple or not.
#
# SUBGOALS
#
# If your program requires users to input the sides in a specific order, change the coding so the user can type in the sides in any order. Rem... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 6 11:34:36 2019
@author: mit
"""
# 학습
from keras.models import Sequential
from keras.layers import MaxPooling2D
from keras.layers import Conv2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.callbacks import ReduceLROnPlateau, EarlyStopping
impo... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 26 17:32:32 2014
@author: swalters
"""
import re
import string
### FILE HANDLING METHODS
def openFile(filename):
''' returns text in a file as a string
input: filename
output: text string
'''
f = open(filename, 'r')
fulltext = f.read()
... |
def reverse(input=''):
str_tmp = ""
for c in input:
str_tmp = c + str_tmp
return str_tmp
|
import gym
from gym import spaces
from gym.utils import seeding
# 定义牌的分数。其中,A = 1, 2-10 = 牌的点数, J/Q/K= 0.5。随机发牌就是随机的从deck中选择一张牌
deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0.5, 0.5, 0.5]
# 人牌值
p_val = 0.5
# 限制值
dest = 10.5
# 随机发牌,随机的从deck中选择一张牌
def draw_card(np_random):
return np_random.choice(deck)
# 随机发到手一张牌
def d... |
# -*- coding:utf-8 -*-
'''
先采用1秒模拟1ms,所有文件sleep 1s 避免线程之间错乱
'''
from mininet.node import Controller
from mininet.log import setLogLevel, info
from mn_wifi.link import wmediumd, adhoc
from mn_wifi.cli import CLI_wifi
from mn_wifi.net import Mininet_wifi
from mn_wifi.wmediumdConnector import interference
from EH.energy ... |
"""Tests for treadmill.ad.*"""
|
from django.shortcuts import render
# Create your views here.
from django.http import JsonResponse
import json
from src.expression.Item import Item
from src.singletons import sku_match
from urllib.parse import unquote
from src.wrappers import autocomplete
from src.Utils.logger import logger
sku_matcher_singleton = sk... |
from enum import Enum
class Direction(Enum):
ASC = 0
DESC = 1
# --------------------insertion sort start --------------------------
def insertion_sort(items, direction=Direction.ASC):
"""
插入排序(inplace)。(以正序来说)从第二个数开始,和前一个数比较,如果比前一个数小,就插到前一个数前面,
然后接着和现在的前一个数比,知道现在的的前一个数比它小了(前头的全比它小),这个位置结束,向
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
while True:
content = input('enter text:')
if content == '':
print('bye')
break
elif content.isdigit():
num = int(content)
if num < 20:
print('a lower num!')
else:
print(num ** 10)
else:
... |
lista = []
while True:
n = int(input('Digite um número: '))
lista.append(n)
resp = str(input('Quer continuar? [S/N] ')).lower().strip()[0]
while 's' not in resp and 'n' not in resp:
resp = str(input('Quer continuar? [S/N] ')).lower().strip()[0]
if 'n' in resp:
break
print('-=' * 30)
... |
input = [list(line.strip() * 100) for line in open('data/03.txt')]
def tree_counting(right, down):
row = col = tree_counter = 0
while row < len(input) - 1:
col += right
row += down
if input[row][col] == '#':
tree_counter += 1
input[row][col] = 'X'
else:
... |
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for c in s:
if c == '(' or c == '[' or c == '{':
stack.append(c)
elif c == ')' or c == ']' or c == '}':
if len(stack) == ... |
from logging import getLogger
import sys
import io
import numpy as np
import PIL.ImageDraw as ImageDraw
import PIL.Image as Image
def cylinder(draw, v1_, v2_, r, **options):
"""
draw a 3D cylinder
"""
options = {"fill": "#fff", **options}
draw.line([int(x) for x in [v1_[0], v1_[1], v2_[0], v2_[1]... |
from common.run_method import RunMethod
import allure
@allure.step("极权限/添加权限")
def permission_addPermission_post(params=None, body=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的环境
:return: 默认... |
from django.shortcuts import render
from django.http import HttpResponseRedirect,HttpResponse
# Create your views here.
def View(request):
return render(request,'textutil.html')
def remove(text):
punc = """~`!@#$%^&*()_-+={}[]"":;\|/?.,<>"""
new = ""
for char in text:
if char not in punc:
... |
# -*- coding: utf-8 -*-
__license__ = """
This file is part of **janitoo** project https://github.com/bibi21000/janitoo.
License : GPL(v3)
**janitoo** is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either vers... |
import unittest
from models.activity import Activity
class TestActivity(unittest.TestCase):
def test_add_activity(self):
self.assertEqual(self.activity.add_activity({"name":"The gods must be crazy"}), "Activity added")
def test_edit_activity(self):
self.assertEqual(self.activity.edit_activi... |
from django.test import TestCase
from recorder.models.site_application import InstantContent
from recorder.models.core import *
class SingleModelTestCase(TestCase):
def setUp(self):
InstantContent.objects.create(contentType=InstantContent.ContentType.TYPE_LOCATION)
def test_user_instant_content(self... |
h1 = hex(97) #h1은 문자열 '0x61'
h2 = hex(98) #h2는 문자열 '0x62'
ret1 = h1+h2
print(ret1) #'0x610x62'가 출력됨
a = int(h1,16)
b = int(h2,16)
ret2 = a+b # ret2는 10진수 195가 됨
print(hex(ret2)) # '0xc3'가 출력
|
from flask import Flask
from flask_restful import Api, Resource
import os
from dotenv import load_dotenv
import mercantile
import requests
import shutil
load_dotenv()
app = Flask(__name__)
api = Api(app)
# Retrieves the API key as an environment variable. Make sure there is a .env file
# in the Platform folder with ... |
import re
import sys
import time
start = time.time()
if len(sys.argv) < 2:
print("We require more vespian command line inputs! (tell me what file to process)")
sys.exit(0)
dev = False
if len(sys.argv) > 2 and sys.argv[2] == "dev":
dev = True
silent = False
if len(sys.argv) > 2 and sys.argv[2] == "silent":
silen... |
cipher = input()
match = ['.', '-.', '--']
for i in range(len(match) - 1, -1, -1):
cipher = cipher.replace(match[i], str(i))
print(cipher)
|
class IntCode():
def __init__(self, input_list):
self.input_list = input_list
self.current_list = input_list
self.current_op = 0
self.output = 0
self.input = 0
'''return the immediate or position value depending on mode in [0,1]'''
def im_pos(self, il, pos, mode):
... |
import numpy as np
import random
# Update centroids
def compute_centroids(X, idx, k):
pixels, n = X.shape
centroids = np.zeros((k,n))
for i in range(k):
nb_samples = 0
for j in range(pixels):
if idx[j] == i:
nb_samples += 1
centroids[i] += X[j]
... |
#-*- coding: utf-8 -*-
#####
#
#Localization for payroll to the Dominican Republic.
#Modifications to the res_partner_bank object.
#
#Author: Carlos Llamacho @ Open Business Solutions
#
#Date: 2013-10-23
#
#####
from openerp.osv import orm, fields, osv
class ResPartnerBank(orm.Model):
_name = 'res.partner.bank'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Defaut:
def __init__(self, provision_travaux_taux,
vacance_locative_taux_T1,
vacance_locative_taux_T2,
gestion_agence_taux):
self._provision_travaux_taux = provision_travaux_taux
self._vacance... |
def duplicate_elements(m, n):
return bool(set(m).intersection(n))
|
#-*- coding:utf8 -*-
# Copyright (c) 2020 barriery
# Python release: 3.7.0
# Create time: 2020-12-21
DATABASE = {
'remote_ip': '39.104.154.79',
'remote_usr': 'wangch',
'remote_pwd': '20191104wc',
'database_usr': 'root',
'database_pwd': '20191104',
'database_name': 'node_infos',
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 29 15:12:20 2019
@author: clair
"""
from imutils.video import VideoStream
import argparse
import imutils
import cv2
from random import randint
import time
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.a... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import List
import pytest
from mtenv.envs.control.cartpole import MTCartPole
from mtenv.wrappers.ntasks_id import NTasksId as NTasksIdWrapper
from tests.utils.utils import validate_mtenv
def get_valid_num_tasks() -> List[int]:
... |
from scrapy.crawler import CrawlerProcess
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from hashlib import md5
from settings import spider_settings
def run_spider():
""" Run VoteSpider as new process """
process = CrawlerProcess(spider_settings)
process.cr... |
from imageai.Detection.Custom import CustomObjectDetection, CustomVideoObjectDetection
import os
import cv2
detector = None
execution_path = os.getcwd()
def load():
# construct and display model
global detector
detector = CustomVideoObjectDetection()
detector.setModelTypeAsYOLOv3()
detector.set... |
# Generated by Django 3.0.5 on 2020-10-31 07:57
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('akun', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Jadw... |
import sys
from pyinit import *
from labels import *
from math import exp
h.celsius = 37
h.load_file("pywrap.hoc")
from conf import *
# determine config file name
def setfcfg ():
fcfg = "netcfg.cfg" # default config file name
for i in xrange(len(sys.argv)):
if sys.argv[i].endswith(".cfg") and os.path.exists(sys... |
__author__ = 'Matthijs'
import ConfigParser;
import StringIO
config = ConfigParser.ConfigParser()
def getConfig():
if len(config.sections()) != 0:
return config
else:
config.read('config.ini')
return config
def loadConfig(contents):
config_buf = StringIO.StringIO(contents)
c... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013-2015 Marcos Organizador de Negocios SRL http://marcos.do
# Write by Eneldo Serrata (eneldo@marcos.do)
#
# This program is free software: you can redistribute it and/or modify
# it un... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.