text stringlengths 38 1.54M |
|---|
from django.db.models import (Model, BooleanField, CharField,CheckConstraint,Q,Deferrable,TextChoices)
class Consent(Model):
"""
Stores Consent to treat.
"""
class Patient (Model):
"""
United States Census Beurau Ethnicity Information. https://www.census.gov/topics/population/race/about.html
... |
import math
import os
from py_scripts import vector_math
from py_scripts.file_handler import append_file
from py_scripts.vector_math import *
from noise import pnoise2
from FilePaths import in_models
# scaling UVs by 3d euclidean distance experiment
def write_obj_quad_tex_len(quad, v_i, fd_v, fd_t, fd_n, fd_f, u_val... |
from unittest import TestCase
import arteria
from arteria.web.routes import RouteService
import mock
class RoutesServiceTest(TestCase):
def test_help_doc_generated(self):
app_svc = mock.MagicMock()
route_svc = RouteService(app_svc, debug=False)
routes = [
("/route0", TestHandler... |
from .context import Description, Context, SharedExamples
from .registry import get_registry
def describe(described, **kwargs):
registry = get_registry()
parent = registry.current_context()
return Description(described,
parent=parent,
**kwargs)
def context... |
# -*- coding: utf-8 -*-
from ._tabular import ClassicTabularNovelty, TabularNovelty, DepthBasedTabularNovelty, DepthBasedTabularNovelty, DepthBasedTabularNoveltyOptimised
from ._base import Feature
from ._state_vars import SVF
_factory_entries = { 'TabularNovelty' : TabularNovelty,\
'ClassicTabula... |
from db_config import db_init as db
# 用户模型
# 数据模型类
class User(db.Model):
#数据库 数据表的名字
__tablename__ = 'user'
# 多个字段
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(255), nullable=False)
password = db.Column(db.String(255), nullable=False)
phone... |
from django.db import models
# Create your models here.
class User(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.CharField(max_length=50)
password = models.CharField(max_length=255)
isAdmin = models.BooleanField(default=False)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
The :mod:`samplesizelib.linear.bayesian` contains classes:
- :class:`samplesizelib.linear.bayesian.APVCEstimator`
- :class:`samplesizelib.linear.bayesian.ACCEstimator`
- :class:`samplesizelib.linear.bayesian.ALCEstimator`
- :class:`samplesizelib.linear.bayesian.MaxUtili... |
from near import near_group
def split2ships(cells):
ships = set()
for i in cells:
new = {i}
add = True
while add:
add = False
for j in cells - new:
intersection = near_group({j}, base=False, diagonals=False) & new
if len(intersection) != 0:
new.add(j)
add = True
ships.add(froz... |
from PIL import Image,ImageFilter
#打开一个jpg图像文件,注意是当前路径
im = Image.open('thumbnail.jpg')
#获得尺寸大小
w,h=im.size
print('Original image size : %sx%s' %(w,h))
im.thumbnail((w*2,h*2))
print('Resize image to :%sx%s' %(w*2,h*2))
im2 = im.filter(ImageFilter.BLUR)
im2.save('thumbnail.jpg','jpeg')
|
''' Class definition for Pre processed contents'''
class PreprocessedContents:
def __init__(
self,
title_text,
normal_text,
media,
embedded_content,
quoted_content):
self.title_text = title_text
self.normal_text = normal_text
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 15 21:13:36 2019
@author: leonwebs
"""
"""
Generate random regions
Randomly form regions given various types of constraints on cardinality and
composition.
This is edited from pysal.region.randomregion to allow weighted cardinality.
For example, total pop... |
import torch.nn as nn
from src.utils.layers import *
scale = 3
class SuperResolutionTransformer(torch.nn.Module):
def __init__(self):
super(SuperResolutionTransformer, self).__init__()
# Initial convolution layers
self.enc_conv0 = nn.Sequential(
ConvLayer(3, 8 * scale, 3),
... |
import requests
from bs4 import BeautifulSoup
baseUrl = "http://www.imdb.com"
#get movie name and make a url to fetch movie details from imdb
def create_url(query):
url ="http://www.imdb.com/find?ref_=nv_sr_fn&q="
query = query.replace(" ","+")
url = url+query+'&s=all'
return url
#extract all the links for a ... |
from dateutil import parser
from rest_framework.test import APITestCase
from .models import Message
from .factories import MessageFactory
class MessageListTestCase(APITestCase):
def test_unauthenticated_user_can_list_all_messages(self):
messages = MessageFactory.create_batch(20)
self.client.force... |
from ellipticCurve import ellipticCurveSolver
from primeChecker import primeChecker
from new_simple import *
from power import powerCongruence
from simply_exp import *
from numsix import *
def show_menu():
print("\"simple\": to calculate a simple linear congruence of style ax = b mod(n)")
print("\"p... |
from typing import Set
from unittest.mock import Mock
from warnings import warn
import spellbot
from spellbot.assets import load_strings
from .constants import REPO_ROOT
S_SPY = Mock(wraps=spellbot.s)
SNAPSHOTS_USED: Set[str] = set()
class TestMeta:
# Tracks the usage of string keys over the entire test sessio... |
"""
This script runs the signal_timestamps function, that gets the duration of each
recording + all the timestamps of the recoring, and saves the info in the
database.
"""
import os
import sqlite3
from birdsong.data_preparation.audio_conversion.signal_extraction import signal_timestamps
if 'HOSTNAME' in os.environ... |
# importing irregular nouns data from irregular_nouns_dict.py (should be in the same folder)
from irregular_nouns_dict import irregular_nouns, nouns_in_plurals
# following English language rules to form plural forms of provided nouns
def plurals(lst):
lst_with_plurals = []
for word in lst:
lst_with_pl... |
import time
from kafka.client import KafkaClient
from kafka.consumer import SimpleConsumer
import os
class Consumer(object):
def __init__(self, addr, group, topic):
self.client = KafkaClient(addr)
self.consumer = SimpleConsumer(self.client, group, topic, max_buffer_size=1310720000)
self.t... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def main():
'''
Following function is the main function that contains the essence of what this script will be doing. Reading the MNIST_100.csv
'''
print("Hello from MNIST_100.csv reader!")
# Create Dataframe
df = pd.rea... |
#!/usr/bin/python3
def print_reversed_list_integer(my_list=[]):
if (my_list):
for index in reversed(range(len(my_list))):
print("{:d}".format(my_list[index]))
|
input_string = input('Which sentence would you like to be reversed?')
split_string =input_string.split()
split_string.reverse()
result = " ".join(split_string)
print(result) |
import urllib2
import json
from operator import itemgetter
import datetime
instructorList = ["weesun", "knmnyn", "wgx731", "Leventhan", "franklingu", "Limy", "Muhammad-Muneer"]
"""
This function fetches the json data for a given username
"""
def fetchJSON(userName):
urlString = "http://osrc.dfm.io/%s.json" % ... |
from .Parameter import Parameter, VerifyFailed
import datetime
__all__ = ['Datetime', 'Date']
class Datetime(Parameter):
'''把 timestamp (int / float) 类型参数值,转换成 datetime 对象'''
rule_order = ['type']
def rule_type(self, value):
if type(value) is datetime.datetime:
return value
e... |
# Generated by Django 2.1.4 on 2019-02-07 18:21
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coreapp', '0080_auto_20190130_0336'),
]
operations = [
migrations.AlterField(
model_name='shipping... |
#!/usr/bin/env python
###############################################################################
#
# Purpose: Create a browse image with 1000 pixels wide from RGB TIF input files.
# Paul G: inclusion of basig FAST format handling
#
# Date: 2012-06-01
# Author: Simon.Oliver@ga.gov.au and Fei.Zhang@ga.g... |
import argparse
import glob
import logging
import os
import random
import timeit
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm, trange
... |
# -*- coding: utf-8 -*-
import datetime
from gmsdk import *
import pandas as pd
import DATA_CONSTANTS as DC
K_MIN_set=[60,300,600,900]
K_MIN=60
exchange_id='DCE'
sec_id='i1801'
md.init(username="smartgang@126.com", password="39314656a")
contractlist=pd.read_excel(DC.PUBLIC_DATA_PATH+'Contract.xlsx')['Contract']
symbol... |
from datetime import datetime
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.operators.dummy_operator import DummyOperator
import json
import pandas as pd
import numpy as np
import datetime
from dateutil.relativedelta import relativedelta
from bs4 import BeautifulSou... |
from ast import Call
import itertools
import json
from typing import (
List,
Any,
Iterable,
TypeVar,
Union,
Dict,
Optional,
Callable,
)
from queue import LifoQueue
from six import string_types
# python 2 to 3 compatibility imports
try:
from itertools import imap as map
from iter... |
#!/usr/bin/python
'''pets'''
# Make an empty list
pets = []
# Make individual pets dictionary
pet = {
'animal type': 'cat',
'name': 'muffin',
'owner': 'adya',
'weight': '2.3 kg',
'eats': 'milk',
}
pets.append(pet)
pet = {
'animal type': 'chicken',
'name': 'kukudu ku',
... |
# Accepted
# Python 3
#!/bin/python3
import sys
s = input().strip()
n = int(input().strip())
l = len(s)
pri = n//l
a = n%l
count, additional = 0, 0
for i in range(l):
if i<a and s[i]=='a':
count += 1
additional += 1
elif s[i]=='a':
count += 1
print((count*pri)+additional)
|
from .columns import Column
class MetaBase(type):
"""
идея __table__ из
https://lectureswww.readthedocs.io/6.www.sync/\
2.codding/9.databases/2.sqlalchemy/3.orm.html
само добавление из
https://realpython.com/python-metaclasses/#custom-metaclasses
и
https://github.com/sqlalchemy/sqlalc... |
from five import grok
from ilo.missionreportstats.content.mission_report_statistics import (
IMissionReportStatistics
)
from ilo.missionreportstats.interfaces import IStatsCache
from zope.lifecycleevent import IObjectModifiedEvent, IObjectAddedEvent
@grok.subscribe(IMissionReportStatistics, IObjectModifiedEvent)
... |
#packages
import json
import requests
#json holen
url = 'https://wttr.in/Darmstadt?format=j1'
r = requests.get(url)
wttr=r.json()
#print(wttr)
currentdate=None
for key in wttr.keys():
if key == 'current_condition':
for j in wttr[key]:
if 'weatherDesc' in j :
pass
... |
from django.db import models
from django.conf import settings
from autoslug import AutoSlugField
from nucleo.models import User, Tag, Dependencia, AreaConocimiento, ProgramaLicenciatura, ProgramaMaestria, ProgramaDoctorado, Proyecto
CURSO_ESPECIALIZACION_TIPO = getattr(settings, 'CURSO_ESPECIALIZACION_TIPO', (('CURSO... |
# -*- encoding: utf-8 -*-
from PyQt4 import QtGui, QtCore
class ListWidgetSpecial(QtGui.QListWidget):
valueSelected = QtCore.pyqtSignal(float)
closeMe = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(ListWidgetSpecial, self).__init__(parent)
self.itemClicked.connect(self.theI... |
def buy_or_pass(stock_price, all_time_high):
if (stock_price <= (.80 * all_time_high)):
return "Buy"
else:
return "Pass"
|
from django.shortcuts import render
from voltageapi.models import measurement
from . import forms
from voltageview.forms import voltapiform,UserForm,UserProfileInfoForm
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponse,HttpResponseRedirect
from django.urls import reverse
fr... |
#! python3
# Author: George Gao, gaojz017@163.com
from django import forms
from .models import Comment
import markdown
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['name', 'email', 'url', 'text']
|
"""Define the command-line interface for the datauniquifier program."""
from pathlib import Path
import os
import psutil
from resource import getrusage, RUSAGE_SELF
import typer
from datauniquifier import analyze
from datauniquifier import extract
from datauniquifier import uniquify
UNIQUE_FUNCTION_BASE = "unique... |
import json
import re
from pybars import Compiler
BLANK_LINE_RE = re.compile(r'\n\s*\n')
def _eq(this, options, a, b):
if a == b:
return options['fn'](this)
return []
def _neq(this, options, a, *args):
for b in args:
if a == b:
return []
return options['fn'](this)
hel... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from rasa_nlu.training_data import load_data
from rasa_nlu.config import RasaNLUModelConfig
from rasa_nlu.model import Trainer, Metadata, Interpreter
from rasa_nlu import... |
import discord
import os
from keep_alive import keep_alive
from discord.ext import commands
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-21 06:01
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('user', '0036_auto_20170620_1646'),
]
operations = ... |
#!/usr/bin/env python
# coding: utf-8
# In[247]:
import pandas as pd
import os
import numpy as np
import matplotlib.pyplot as plt
# In[275]:
def fetch_housing_data():
return pd.read_csv(r"converted_rent_only.csv", 'r')
# In[274]:
def filter(housingData):
housingData = housingData[housingData[... |
# Generated by Django 2.1.3 on 2019-02-18 18:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fest_2019', '0032_auto_20190218_1131'),
]
operations = [
migrations.AddField(
model_name='caracterizacioninicial',
n... |
from TreeNode import TreeNode
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
else:
return self.isSymmetrucLeftRight(root.left,root.right)
def isSymmetrucLeftRig... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayEbppInstserviceTokenCreateResponse(AlipayResponse):
def __init__(self):
super(AlipayEbppInstserviceTokenCreateResponse, self).__init__()
self._sign_token = None... |
left = 1
right = 22
def selfDividingNumbers(left, right):
alist= []
for i in range(left,right+1):
judge = 0
if "0" in list(str(i)):
continue
for num in list(str(i)):
if i % int(num) == 0:
judge = 1
continue
else:
... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from ..context.dataindex import makeindex
from ..context.missing import is_missing
from .. import errors
from ..document import Document
from ..elements.elementbasemeta import ElementBaseMeta
from ..co... |
import socket
import struct
from uuid import getnode as get_mac
from random import randint
class DHCPDiscover:
def buildPacket(self):
packet = b''
packet += b'\x01' #OP
packet += b'\x01' #HTYPE
packet += b'\x06' #HLEN
packet += b'\x00' #HOPS
packet += b'\x39\x03\xF3\x26' #XID
packet += b'\x00\x00' #SECS... |
import os
import pickle
import requests
import youtube_dl
import datetime
from bookmark import FileBookmark
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from pprint import pprint
class YoutubeVideos:... |
from unittest.mock import *
from unittest import TestCase, main
from assertpy import assert_that
from src.serviceOrders import Order
from src.dataOrders import OrdersData
from src.dataProductsOrders import OrdersProductsData
class testDeleteOrder(TestCase):
def setUp(self):
self.temp = Order()
sel... |
import pandas as pd
import re
def cast_as_bool(df):
# sorry...this is messy. just checks to see if there are columns w/data type of float and 1,0
# then casts as bool
for col in df.columns.values:
if df[col].dtype == "float64":
if len(df[col].unique()) == 2 \
an... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.display import display
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
customers = pd.read_csv('StudentsPerformance.csv')
display... |
# -*- coding: utf-8 -*-
import sys
import datetime
import logging
import pymysql
from dbhelper import DBHelper
sys.path.append('../utils/')
from fileutil import FileUtil
class RESHelper():
logger = logging.getLogger('RESHelper')
def __init__(self):
self.dbHelper=DBHelper()
self.resFileName =... |
# Generated by Django 2.2.7 on 2019-11-24 23:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auctions_service', '0002_bids_most_current_bid'),
]
operations = [
migrations.AlterField(
model_name='bids',
name='b... |
from datetime import datetime
import unittest
from home_eye.model.sensor import Sensor
class SensorTest(unittest.TestCase):
def test_parameters_in_to_json(self):
sensor = Sensor('indoor', 12.0, 55.5, datetime.now())
sensor_json = sensor.to_json()
self.assertIn('name', sensor_json)
... |
" Method containing activation functions"
from torch.optim import Adam, AdamW, SGD
from src.utils.mapper import configmapper
configmapper.map("optimizers", "adam")(Adam)
configmapper.map("optimizers", "adam_w")(AdamW)
configmapper.map("optimizers", "sgd")(SGD)
|
from pyspark.sql import SparkSession
from pyspark.sql import SQLContext, HiveContext
from pyspark import SparkContext
from pyspark.sql.functions import udf
from pyspark.sql.functions import *
from pyspark.sql.types import *
from pyspark.sql.window import Window
import pyspark.sql.functions as F
import numpy as np
imp... |
import matplotlib.pyplot as plt
method=['PBE','PBE-D2','PBE-D3','RPBE','RPBE-D2','RPBE-D3','revPBE','rPW86','optPBE','optB88','optB86b']
lat=[0.209,0.652,0.456,0.036,0.440,0.417,0.255,0.364,0.383,0.427,0.458]
plt.bar(method,lat, color='r',width=0.35)
#plt.axvline(y=3.923)
plt.xlabel('Dispersion Method')
#plt.axhline(y=... |
import requests
API_KEY = '8793610e7c4019ccd6189b9bc7bad61e'
parameters = {
"lat": 44.4323,
"lon": 26.1063,
"appid": "8793610e7c4019ccd6189b9bc7bad61e",
"exclude": 'current,minutely,daily'
}
response = requests.get(
url='https://api.openweathermap.org/data/2.5/onecall', params=paramet... |
import sys
from _typeshed import BytesPath, StrOrBytesPath, StrPath
from genericpath import (
commonprefix as commonprefix,
exists as exists,
getatime as getatime,
getctime as getctime,
getmtime as getmtime,
getsize as getsize,
isdir as isdir,
isfile as isfile,
samefile as samefile,
... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^process_reg$',views.process_reg),
url(r'^process_log$',views.process_log),
url(r'^dashboard$', views.dashboard),
url(r'^logout$', views.logout),
url(r'^trips/new$', views.new),
url(r'^pro... |
# Created by MechAviv
# Map ID :: 402000620
# Sandstorm Zone : Refuge Border
if sm.hasQuest(34929):
sm.spawnNpc(3001509, 298, 200)
sm.showNpcSpecialActionByTemplateId(3001509, "summon", 0)
sm.spawnNpc(3001512, 374, 200)
sm.showNpcSpecialActionByTemplateId(3001512, "summon", 0)
sm.spawnNpc(3001513, 4... |
from lstm_model import LSTM_Model,CHECKPOINT_PATH,log_dir,NUM_EPOCH,run_epoch
from transform2Tfrecord import makeDataSet
import tensorflow as tf
train_files = './result/TEST/try_multiple.tfrecords'
if __name__ == '__main__':
# init = tf.random_uniform_initializer(-2,2)
with tf.variable_scope('LSTM_model', reu... |
# -*- coding: utf-8 -*-
"""
@author: carlos
"""
import csv
# La siguiente función ayuda al usuario a definir que reporte quiere
# generar
def elegir_reporte():
print("¿Qué reporte desea generar?")
print("-----------------------------------------------")
print("1) Rutas de importación y exportación")
p... |
n=int(input())
if(n%2==1):
print(1)
else:
x=n
while(n>0):
n//=2
if(n%2==1):
break
print(x//n)
|
import os
import random
import cv2
import struct
import numpy as np
import tensorflow as tf
from .utilize import semantic_down_sample_voxel
np.seterr(divide='ignore', invalid='ignore')
DATA_DIR = os.path.join(os.environ['HOME'], 'datasets', 'SUNCG')
RECORD_DIR = os.path.join(os.environ['HOME'], 'datasets', 'SUNCG-TF... |
###
# DP
# State: dp[i]: min cost to i
# Function: dp[i] = dp[j] + A[j] for j < i
# Initialization: dp[0] = 0
# Answer: dp[n]
# Time Complexity: O(n^2)
# Space Complexity: O(n)
###
class Solution(object):
def cheapestJump(self, A, B):
"""
:type A: List[int]
:type B: int
:rtype: List[... |
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from site_utility.models import Counties, Cities
from school.models import Facultati, Specializari
from prof.models import Profesori
from school.views import counties
from django.http import HttpResponse, JsonResponse
# ... |
import unittest
class TestRow(unittest.TestCase):
def test___init__(self):
from row import Row
from database import Database
try:
import os
os.remove('test_Row.__init__.db')
except OSError:
pass
db = Database('test_Row.__init__.db')
... |
#!/usr/bin/env python
#coding:utf-8
import numpy as np
from visualdl import LogWriter
class MyLog():
def __init__(self,mode="train",logDir="../log"):
self.mode=mode
self.varDic={}
self.log_writer = LogWriter(logDir, sync_cycle=10)
def... |
import sys
sys.stdin = open("D3_17319_input.txt", "r")
T = int(input())
for test_case in range(T):
N = int(input())
s = input()
print("#{} {}".format(test_case + 1, "Yes" if N % 2 == 0 and s[:N // 2] == s[N // 2:] else "No")) |
# coding = utf-8
"""
@author: zhou
@time:2019/2/15 15:41
"""
from sklearn.cluster import KMeans
from sklearn.preprocessing import MinMaxScaler
import pandas as pd
def zuqiu_kmeans(n):
data = pd.read_csv('data.csv', encoding='gbk')
# print(data)
train_x = data[['2019年国际排名', '2018世界杯', '2015亚洲杯']]
# 初始... |
# code has been inferred from https://github.com/aGIToz/kFineTuning/blob/master/finetune.py
# https://keras.io/preprocessing/image/
import os
import seaborn as sns
import itertools
import numpy as np
import sys
import pandas as pd
import xml.etree.ElementTree as ET
from PIL import Image
from collections import Counte... |
import os
import logging
from flask import Flask, url_for as _url_for
from flask.ext.oauth import OAuth
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.migrate import Migrate
from elasticsearch import Elasticsearch
from celery import Celery
from grano import default_settings
logging.basicConfig(level=logg... |
# TrackAnalysisWidget.py
# (C)2014
# Scott Ernst
from __future__ import print_function, absolute_import, unicode_literals, division
from pyglass.threading.FunctionRemoteExecutionThread import FunctionRemoteExecutionThread
from pyglass.widgets.PyGlassWidget import PyGlassWidget
#_____________________________________... |
"""
Ax_Metrics - Query component for time frame specification
------------------------------------------------------------------------------
Author: Dan Kamins <dos at axonchisel dot net>
Copyright (c) 2014 Dan Kamins, AxonChisel.net
"""
# ----------------------------------------------------------------------------
... |
from search import *
loopFlag = True
def printMenu():
print("=================== 메 뉴 ==================")
print("1. 종료")
print("2. 보호소 검색")
print("3. 유기동물 검색")
print("===========================================")
def launcherFunction(menu):
if menu == '1':
Quit()
elif menu == '2':
... |
def standaardtarief(afstandKM):
if afstandKM > 50:
output = 15 + afstandKM*.6
else:
output = afstandKM*.8
if afstandKM < 0:
output = 0
return output
def ritprijs(leeftijd, weekendrit, afstandKM):
if weekendrit == "ja" :
if leeftijd < 12 or leeftijd >= 65:
... |
import turtle
smart = turtle.Turtle()
# Loop 4 times. Everything I want to repeat is
# *indented* by four spaces.
for i in range(4):
smart.forward(50)
smart.right(90)
# This isn't indented, so we aren't repeating it.
turtle.done() |
a = int(input().split()[4])
b = int(input().split()[4])
total = 0
for i in range(40000000):
a = (a * 16807) % 2147483647
b = (b * 48271) % 2147483647
if bin(a)[-16:] == bin(b)[-16:]:
total += 1
print(total) |
#enter display message
print("welcome to YOU CAN VOTE program")
#enter input from user
usr_name = str(input("enter your nationality :"))
usr_age = int(input("enter your age :"))
usr_anti = str(input("are you anti nationalist ? : (y/n)"))
# using condition
if usr_name =="indian" and usr_age >= 18 and usr_anti == "n"... |
import random, os
from time import sleep
v = 'rock', 'paper', 'scissor'
print(v)
sleep(1)
thing = input('Enter your things : ')
sleep(1)
if thing == 'rock':
z = random.choice(v)
sleep(1)
print(z)
sleep(1)
if z == 'paper':
print('i won! ')
input(' ')
exit()
... |
'''
Class Interactions
Class User
'''
from collections import Counter
import pickle
from pymongo import MongoClient
from Tweet import Tweet
class Interactions:
FILE = "../data/TheGoodPlace/TheGoodPlace.csv"
COLLECTION = "old_tweets"
OUTPUT_FILE = "TheGoodPlace_interactions.p"
HOST = "10.1.10.96" # ... |
#!/usr/bin/env python
import unittest
import logging
from testsmtpd import SSLSMTPServer, TestCredentialValidator
import os
import secure_smtpd
from datetime import datetime, timedelta
class RpiSecurityCamTest(unittest.TestCase):
_smtp_server = None
TEST_DIR = 'test_dir'
def _cleanup_file(self, file_name):... |
''' Insert heading comments here.'''
import math
EPSILON = 1.0e-7
def display_options():
''' This function displays the menu of options'''
MENU = '''\nPlease choose one of the options below:
A. Display the sum of squares of the first N natural numbers.
B. Display the appro... |
import dash
import dash_core_components as dcc
import dash_html_components as html
import matplotlib.pyplot as plt
from dash.dependencies import Input, Output
import plotly.offline as py
from plotly.graph_objs import *
import plotly.graph_objs as go
import dash_bootstrap_components as dbc
import folium
... |
import re
import pandas
import os
import file_manager as fm
MAX_SIZE = 200
MIN_SIZE = 180
progress = 1
def save_csv(filename_in, filename_out, data, mode='a'):
"""" Encode file to the csv (row for each file) """
df = pandas.DataFrame(data=[data])
df.to_csv(filename_out, sep=',', index=False, header=False... |
from enum import Enum
# noinspection PyCompatibility
def objTypeCheck(obj, parentType, objName):
if issubclass(parentType, Enum):
if obj not in [et.value for et in parentType]:
raise ValueError(f"Invalid value for {objName}:{obj}")
return
if not isinstance(obj, parentType):
... |
import pandas as pd
import numpy as np
from scipy.optimize import minimize
def van(tir, cf):
'''
Return VAN
tir = interest rate
cf = (array) cash flows
'''
if not isinstance(cf, np.ndarray): return('cf must be an array')
v = 1 / (1 + tir) ** np.arange(cf.size)
van = cf * v
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-06-18 16:04
from __future__ import unicode_literals
import DjangoUeditor.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('firstapp', '0015_auto_20170615_1344'),
]
operations = [
... |
from selenium import webdriver
import yaml
#获取页面cookies
def test_get_cookies():
driver = webdriver.Chrome()
driver.get('https://e1sm0k24i2.feishu.cn/calendar/week')
input("please input enter to continue")
cookie = driver.get_cookies()
with open("cookie_data.yaml", "w", encoding="UTF-8") as f:
... |
import math
import random
import time
from collections import deque, defaultdict, Counter
from typing import Tuple, List, Union
import numpy as np
import torch
from agents.belief_agent import BeliefBasedAgent
from agents.models.model_based_models import RewardModel, TransitionModel
from agents.models.multitask_models... |
with open('Day 5/input.txt') as f:
for intcode in f:
original_intcode = list(map(int, intcode.strip().split(',')))
intcode = original_intcode.copy()
program_input = 5
p = 0
jump = False
modes = []
while True:
# Opcode handler #
if intcode[p] == (3 or 4 or 99):
opcode = intcode[p]
else:... |
# https://github.com/Star-Clouds/CenterFace
from centerface.centerface_model import CenterFace
from common.det_face import DetFace
Name = 'CenterFace'
def __load_model():
return CenterFace()
__model = __load_model()
def detect_faces(frame, thresh=0.2):
h, w = frame.shape[:2]
faces, _ = __model(fr... |
import re
import requests
import json
def getObjectsFromAPI(sentence):
sentence = re.sub(r'(?<!\d)\.(?!\d)', ' .', sentence)
text = '+'.join(sentence.split(' '))
url = 'http://bioai8core.fulton.asu.edu/kparser/ParserServlet?text='+text+'&useCoreference=false'
r1 = requests.get(url)
try:
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.