text stringlengths 38 1.54M |
|---|
import dataset
import tensorflow as tf
import time
from datetime import timedelta
import math
import random
import numpy as np
def create_weights(shape):
return tf.Variable(tf.truncated_normal(shape, stddev=0.05))
def create_biases(size):
return tf.Variable(tf.constant(0.05, shape=[size]))
def create_convo... |
# Generated by Django 2.0 on 2017-12-19 16:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('character_builder', '0004_auto_20171218_2217'),
]
operations = [
migrations.RemoveField(
model_name='racetrait',
name=... |
# Volatility
# Copyright (C) 2007-2013 Volatility Foundation
# Copyright (c) 2008 Brendan Dolan-Gavitt <bdolangavitt@wesleyan.edu>
#
# Additional Authors:
# Mike Auty <mike.auty@gmail.com>
#
# This file is part of Volatility.
#
# Volatility is free software; you can redistribute it and/or modify
# it under the terms of... |
# Copyright 2019 Yelp 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 writing, so... |
import datetime
from django.shortcuts import render
#DataFlair #Views #TemplateInheritance
def home(request):
context = {'k2' : 'Welcome to the Second Page'}
return render(request, 'home/base.html', context)
def other(request):
context = {'k1': 'Welcome to the Second page', }
return render(request, 'ho... |
def fizz_buzz():
for num in range(101):
if num % 3 == 0 and num % 5 == 0:
print(num)
print("Fizz_Buzz")
elif num % 3 == 0:
print(num)
print ("Fizz")
elif num % 5 == 0:
print (num)
print ("Buzz")
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-04-24 20:48
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0019_allow_null_precision'),
]
operations = [
migrations.Alter... |
from django.db import models
from django.urls import reverse
import datetime
from django.contrib.auth import get_user_model
User = get_user_model()
class Chatroom(models.Model):
name = models.CharField(max_length = 255)
description = models.CharField(max_length = 100)
posted = models.DateField(default=dat... |
#from zinc_id.get_zincid import get_zincid_from_smile
#zinc_id = get_zincid_from_smile("FC(F)(F)C1=CC=C(NC(=O)CSC2=NC(=CC=N2)C2=CC(=NO2)C2=CC=C(Cl)C=C2Cl)C=C1")
#print(zinc_id)
from padelpy import from_smiles
#calculate molecular descriptors for propane
descriptors = from_smiles('FC(F)(F)C1=CC=C(NC(=O)CSC2=NC(=C... |
import numpy as np
class Node(object):
def __init__(self, item, next_note=None):
self._item = item
self._next = next_note
def append(self, item):
head = self
while head._next != None:
head = head._next
head._next = item if isinstance(item, Node) else Node(item)
def __repr__(self):
return ... |
matrix = []
for i in range(3):
line = []
for j in range(3):
line.append(eval(input('Input column {}, row {}: '.format(i + 1, j + 1))))
matrix.append(line)
k = eval(input('Input k: '))
print('Matrix before multiplying: ', matrix)
for i in range(3):
matrix[i][i] *= k #the main di... |
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
def home(request):
return render_to_response('index.html')
def login(request):
c={}
c.update(csrf(request... |
# Generated by Django 3.1.6 on 2021-02-02 10:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='TableFirst',
fields=[
... |
# coding=utf-8
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
from... |
#!/usr/bin/env python
import sys,string
import astropy.io.fits as pyfits
def usage() :
print sys.argv[0], "-k key1 -k key2 ... file1 file2 ... (-hdu #)"
sys.exit(0)
if len(sys.argv)<2 :
usage()
filenames=[]
keys=[]
hdu=0
i=1
while i<len(sys.argv) :
arg=sys.argv[i]
if arg[0]!='-' :
fi... |
#
# trimt8p
# Version: 0.1
#
import sys
import os.path
import base64
import binascii
import StringIO
# Debug-mode
debug = False
def main():
if len(sys.argv) < 2:
print("Usage: %s t8p_file_1 [t8p_file_N]" % sys.argv[0])
exit(1)
for idx, arg in enumerate(sys.argv):
if... |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
class Zomato:
def __init__ (self):
options = Options ()
options.binary_location = "/usr/bin/brave"
# options.add_argument ('--headless')
self.driver = webdriver.Chrome(options = options)
def f... |
def is_leap (year):
# print(year)
if (year %4 == 0 or year % 400== 0):
print(" true, the year is evenly divided by 4, 400")
elif (year % 100 == 0):
print(" false, the year is divided by 100 is not a leap year")
# return year
years = int(input("enter the year :"))
is_leap(year... |
n=input()
n=list(n)
for i in range(len(n)):
n[i]=list(n[i])
numbers='1234567890'
numbers=list(numbers)
for k in range(len(numbers)):
for l in range(len(n)):
if(n[l][0]==numbers[k]):
n[l][0]=int(n[l][0])
if(n[8][0]=="A"):
if(n[0][0]==1 and n[1][0]==2):
n[1][0]=0
n[0][0]... |
#!/usr/bin/env python
# Create thresholded matrices
'''
Threshold matrices by a certain cost
It's important to give it an integer number of
elements to keep though as the rounding causes
difficulty calculating the correct value
'''
#=============================================================================
# IMPO... |
"""
IFT 6135 - W2019 - Practical Assignment 1 - Question 1
Assignment Instructions: https://www.overleaf.com/read/msxwmbbvfxrd
Github Repository: https://github.com/stefanwapnick/IFT6135PracticalAssignments
Developed in Python 3
Mohamed Amine (UdeM ID: 20150893)
Oussema Keskes (UdeM ID: 20145195)
Stephan Tran (UdeM ID... |
import os
import re
import json
import hashlib
import random
import requests
import threading
from flask import Flask, render_template, request, redirect, session, jsonify
import psycopg2
from app import config
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 #############WARNING: remove... |
#json_schema to KV
import sys, os
import pandas as pd
import json, re, copy
from itertools import groupby
LIST_SPLITTER='!|!'
get_type_str=lambda obj:str(type(obj)).replace("'",'').strip().split(' ')[1].replace('>','')
def detect_type(obj):
ts=get_type_str(obj)
obj_sz=len(str(obj))
leaf=True
if ts in... |
"""
This module handles pure systematics within VICE.
"""
from __future__ import absolute_import
try:
__VICE_SETUP__
except NameError:
__VICE_SETUP__ = False
if __VICE_SETUP__:
from ._build import write_build as _write_build
from ._build import check_cython as _check_cython
__all__ = ["_write_build", "... |
import yaml
import logging
import argparse
from model import train, predict
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('--mode', type=str, choices=['train', 'predict'],
help='mode to run the script, either train, predict, or evaluate')
parser.ad... |
# -*- coding: utf-8 -*-
'''
Created on Jul 9, 2013
@author: Chunwei Yan @ pkusz
@mail: yanchunwei@outlook.com
'''
import sys
import re
class CodinError(Exception):
def __init__(self, msg):
self.msg = msg
class CurCodeRuntimeError(CodinError):
def __init__(self, msg):
CodinError.__init__(sel... |
#!/usr/bin/env python
# coding: utf-8
from __future__ import (absolute_import, division,
print_function, unicode_literals)
try:
# noinspection PyUnresolvedReferences, PyCompatibility
from builtins import * # noqa
except ImportError:
pass
import os
import pandas as pd
from climate... |
# Во втором массиве сохранить индексы четных элементов первого массива.
# Например, если дан массив со значениями 8, 3, 15, 6, 4, 2, второй массив
# надо заполнить значениями 0, 3, 4, 5 (помните, что индексация начинается с
# нуля), т. к. именно в этих позициях первого массива стоят четные числа.
def gen_list(n, m, l):... |
#! /usr/bin/env python3
"""
Read in the "show_arp.txt" file using the readlines() method.
Use a list slice to remove the header line.
Use pretty print to print out the resulting list to the screen, syntax is:
from pprint import pprint
pprint(some_var)
Use the list .sort() method to sort the list based on IP addre... |
'''
Created on Jul 02, 2012
@author: mkraus
'''
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
class PlotVorticity2D(object):
'''
classdocs
'''
def __init__(self, diagnostics, output=False):
'''
Constructor
'''
self.diagnostics = diagn... |
import sqlite3 as db
def studentdata():
con=db.connect("datafile")
cur=con.cursor()
cur.execute("create table if not exists student(std_id integer primary key,first_name text,sur_name text,dob text,age text,gender text,address text,\
mobile text)")
con.commit()
con.close()
def addn... |
#!/usr/bin/python3
# Set two variables, with a true and false value
t = True
f = False
# t is true, so the if statement gets executed!
if (t):
print("True!")
# f is false, so this statement doesn't
if (f):
print("This will never be printed!")
# not false = true, so this statement gets executed
if (not f):
print(... |
number = int(input('Enter a number: '))
for n in range(1, number+1):
is_prime = True
i = 2
while i < n and is_prime:
if n % i == 0:
is_prime = False
else:
i += 1
if is_prime:
print(n)
|
import copy
import logging
import matplotlib.pyplot as plt
import numpy as np
import os
import dill
from scipy.stats import wilcoxon
import SimpleITK as sitk
import time
import xlsxwriter
import functions.setting.setting_utils as su
from .image import landmark_info
def calculate_write_landmark(setting, pair_info, ove... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 25 12:46:58 2017
@author: Jason
"""
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import BayesianRidge
f... |
from enum import Enum
import logging
import inspect
import datetime
import os
LOGGER = logging.getLogger(__name__)
class DataSource:
def __init__(self):
self.status = Status.INITIALIZED
self._last_get_dt = datetime.datetime.now() - datetime.timedelta(seconds=60)
self._current_payload = {}
... |
from monty.extension.basic import BasicExtension
from monty.cli.stream import *
from monty.config.loader import get_cfg
from pprint import pprint
class MontyCliExtension(BasicExtension):
"""
Extension: user
"""
namespace = "config"
config = None
def __init__(self):
self.commands = {
... |
from urllib.request import urlopen
import json
def load_web_json(path):
with urlopen(path) as response:
return json.loads(response.read().decode('utf-8'))
if __name__ == "__main__":
topsong = load_web_json("https://itunes.apple.com/us/rss/topsongs/limit=50/genre=29/explicit=true/json")
print(jso... |
from enum import Enum
from json import dumps, loads
class TipoPedido(Enum):
CADASTRO_USUARIO = 0
LOGIN = 1
ATUALIZAR_LISTA_CLIENTES = 2
ATUALIZAR_LISTA_GRUPOS = 3
MENSSAGEM_PRIVADA = 4
MENSSAGEM_GRUPO = 5
CADASTRO_GRUPO = 6
DESCONECTAR = 7
MENSAGEMS_PRIVADAS_ARQUIVADAS = 8
MENS... |
from socket import *
if __name__=='__main__':
host = 'localhost'
port = 21000
buffer_size = 1024
address = (host, port)
#create a socket (network oriented, connectionless)
client_socket = socket(AF_INET, SOCK_DGRAM)
while True:
answer = input('write something:')
if not ans... |
#!/usr/servers/env python
# -*- coding: utf8 -*-
#
# $Id$
#
# Copyright (c) 2012-2014 "dark[-at-]gotohack.org"
#
# This file is part of pymobiledevice
#
# pymobiledevice 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 Fou... |
"""Script to do all the work:
- generate dataset
- train the model
"""
import os
import argparse
import shutil
from training.data import nosify_dataset
from utils import generate_vocab, split_dataset, sent_tokenizer
import seq2seq
def main():
"""Contains all of the work that needs to be done."""
args = parse_... |
from display import *
def draw_line( x0, y0, x1, y1, screen, color ):
if x1 < x0:
tempX = x0
tempY = y0
x0 = x1
y0 = y1
x1 = tempX
y1 = tempY
if (x0 == x1):
m = 2
else:
m = (y1 - y0)/(x1-x0)
if (m > 0):
if (m < 1):
dr... |
import pyarrow.parquet as pq
import numpy as np
import pandas as pd
import pyarrow as pa
#Read a single parquet file locally like this:
path = "/Users/sbommireddy/Documents/python/assignments/dq/dataformats/part-00000-4e165a94-46c6-43bb-919e-706543c5dd8f-c000.snappy.parquet"
table = pq.read_table(path)
df = table.to_... |
import matplotlib.pyplot as plt
from sklearn.datasets.samples_generator import make_regression
X, y, coef = make_regression(n_samples=1000, n_features=1, noise=10, coef=True)
plt.scatter(X, y, color='black')
plt.plot(X, X * coef, color='blue', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()
|
import logging
from .escape_codes import escape_codes, parse_colors
default_log_colors = {
'DEBUG': 'green',
'INFO': 'thin_white',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bold_purple'
}
class ColorizedRecord(object):
"""
Wraps a log record, adding named escape codes to the internal dict.
Th... |
import numpy as np
class AdaGrad:
def __init__(self, lr):
self.lr_ = lr
self.h_ = None
def update(self, params, grad):
if self.h_ is None:
self.h_ = {}
for key, val in params.items():
self.h_[key] = np.zeros_like(val)
for key in params.k... |
# Generated by Django 2.2.5 on 2019-10-25 01:41
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sport', '0003_field_status'),
]
operations = [
migrations.CreateModel(
name='Image',
... |
from abc import ABC, abstractmethod
from math import pi
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def circ(self):
pass
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return pi*self.r*self.r
def circ(self... |
import unittest
from copy import deepcopy
from datetime import datetime
from io import BytesIO
from pathlib import Path
import numpy as np
import pytest
from pydicom.data import get_testdata_file, get_testdata_files
from pydicom.dataset import Dataset
from pydicom.filereader import dcmread
from pydicom.sr.codedict im... |
# -*- coding: utf-8 -*-
import numpy as np
import serial
import os
import six.moves.urllib as urllib
import sys
import time
import tarfile
import tensorflow as tf
from PIL import Image
# import the necessary packages
from skimage.measure import structural_similarity as ssim
import matplotlib.pyplot as p... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
get_ipython().magic(u'matplotlib inli... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 14 20:12:55 2017
@author: Anders
"""
import os
import pandas as pd
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
from functions import make_box
import numpy as np
print('making overall bar graph')
plotly.tools.set_crede... |
from flask import g
from brainminer.base.api import LoginProtectedResource
from brainminer.auth.authentication import create_token
# ----------------------------------------------------------------------------------------------------------------------
class TokensResource(LoginProtectedResource):
URI = '/tokens'... |
from django import forms
from django.forms import ModelForm, DateInput, DateTimeInput, PasswordInput, IntegerField
from .models import *
class AnoLetivoForm(ModelForm):
required_css_class = 'required'
class Meta:
model = AnoLetivo
dateinput = DateInput()
dateinput.input_type = 'date'
... |
# coding: utf-8
# In[76]:
from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
# In[1]:
# Constantes
n1 = 1.3 #Poder de la gasolina 1
n2 = 1.3 #Poder de la gasolina 2
k = 1.4 #Coeficiente calorífico de los gases
r = 0.287 #Consta... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# blazars from Fan et al. (2016), obtained from the 3FGL telescope at Fermi.
# In[0]: read and parse data; 999 sources with known redshift
from __future__ import division
import csv
import numpy as np
import quasars as quas
from quasars import QuasarData, Band
import matp... |
class Cliente:
'''
Ocultamiento de información:
Los métodos y atributos débilmente privados tienen un único guion bajo al principio.
Esto señala que son privados, y no deberían ser utilizados por código externo.
Sin embargo, es en su mayor parte solo una convención, y no impide que el código... |
# coding=utf-8
'''
客户端2,功能:计算数字的 2倍
'''
# 导入包
import socket, time
# 为了打印日志更好看
tag = "===============".encode()
# 接收服务器的数字
recv_num = ""
# 计算数字后,发送给服务器的消息
send_msg = ""
# 创建套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器,9000为服务器端口号
sock.connect(("127.0.0.1", 9000))
# 循环发送接收消息,客户端先发消息
while T... |
import random
import _util_prepare_ as util
import os
import shutil
"""given a csv it splits it two, one to be kept as it is and another to be augmented"""
"""FUNDAMENTAL ARGS"""
"""where to find original csv"""
csv_path = 'train.age_detected.csv'
"""where to print csvs"""
output_path = "./temp_csvs/"
"""au... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 21 16:02:58 2016
@author: cs390mb
Speaker Identification : Training a Classifier
This script trains a classifier for identifying speaker from audio data.
The script loads all labelled speaker audio data files in the specified directory.
It extracts features from the r... |
from PyQt5.QtWidgets import QFileDialog
from SettingComponents.Components.Textbox import ParentTextbox
class PathBox(ParentTextbox):
def __init__(self, parent=None, jsondata=None):
super().__init__(parent=parent, jsondata=jsondata)
self.default_width = 250
self.default_height = 10
self.setFixedWidth(self.... |
__author__ = "Bharat Medasani"
__copyright__ = "Copyright 2012, The Materials Project"
__maintainer__ = "Bharat Medasani"
__email__ = "mbkumar@gmail.com"
__date__ = "7/01/14"
import datetime
import filecmp
import glob
import os
import shutil
import time
import unittest
from multiprocessing import Process
from monty.o... |
password = 'a123456'
x = 3
while True:
pw = input('Enter password: ')
if pw == password:
print('correct password')
break
else:
x = x - 1
print('you still can try' , x ,'times')
if x == 0:
print('sorry, you cannot try anymore')
break
|
character_name = "mike"
character_age = "70"
print("There once was a man named " + character_name + ".")
print("he was " + character_age + " years old ")
character_name = "tom"
print("i updated the variable inside of my program over here :D")
print("he really liked the name " + character_name + " ")
print("b... |
from django.contrib.auth import get_user_model
from django.shortcuts import render
from django.contrib.auth import login as auth_login
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
from django.views.generic import ListView, UpdateView
from .forms import SignUpForm
... |
from test_map_base import TestMapBase
from unittest.mock import call, patch
from werkzeug.datastructures import OrderedMultiDict
from io import BytesIO
from mrt_file_server.utils.nbt_utils import load_compressed_nbt_file, get_nbt_map_value
import os
import pytest
class TestMapUpload(TestMapBase):
def setup(self):
... |
#%%
if '__file__' in globals():
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from os import pread
import numpy as np
from dezero.models import VGG16
model = VGG16(pretrained=True)
x = np.random.randn(1,3,224,224).astype(np.float32)
model.plot(x)
# %%
import dezero
from PIL imp... |
# -*- coding: utf-8 -*-
"""
Batch URL expander
Note: Speed up messy data by expanding only known short URLs
(c) Kevin Driscoll, 2014
"""
from socket import error as SocketError
import fileinput
import multiprocessing
import re
import urllib
import urllib2
# Constants
USER_AGENT = u'shortURL lengthener/0.1 +http:/... |
import os, re, yaml
import locale as localepy
LANG_ROOT = os.path.join(os.path.dirname(__file__), "langs")
locales = ['en_US', 'fr_FR', 'vi_VN', 'zh_HANS']
substitutes = {'fr': 'fr_FR', 'en': 'en_US', 'vn': 'vi_VN', 'zh': 'zh_HANS', 'zh_CN': 'zh_HANS'}
LANG = dict()
loaded = dict((locale, False) for locale in locales... |
from pyautogui import *
from pyperclip import *
a = ["Minhoca, minhoca",
"Me dá uma beijoca",
"Não dou, não dou",
"Então eu vou roubar",
"Minhoco, minhoco",
"Você é mesmo louco",
"Beijou do lado errado",
"A boca é do outro lado",
]
while True:
if True:
click(1100, 7... |
'''
Created on 27.06.2017
@author: Peer
'''
from bson.code import Code
import os
import pathlib
import pymongo
TRANSLATION_TABLE = (('.', '\uff0e'),
('$', '\uff04'))
class GitExplorerBase(object):
@staticmethod
def get_gitexplorer_database():
'''Returns the MongoDB for gitex... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Datasets module.
"""
import numpy as np
import logging
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from loader import MNIST_bis
from custom_transform import RandomTranslation, Substract
from utils import train_valid_split... |
import threading
import time
condition = threading.Condition()
item = 0
def producer():
global condition
global item
condition.acquire()
time.sleep(1)
item += 1
print('NOTIFY!')
condition.notify()
condition.release()
def consumer():
global condition
global item
condition.acquire()
while not item:
con... |
"""Player File"""
from stats import HasStats
from inven import HasInventory
class Player has (HasStats, HasInventory):
pass
|
import re
from iso4217 import Currency as iso4217_Currency
from pysecm.ric import RIC
class CurrencyRIC(RIC):
# Regex
_re_iso4217 = r'[A-Z]{1,3}'
_re_ric = rf'^{_re_iso4217}{_re_iso4217}$'
def __init__(self, ric_str: str):
if not CurrencyRIC._is_valid_str(ric_str):
raise ValueEr... |
#/usr/bin/python2
# -*- coding: utf-8 -*-
__author__ = 'ins3c7 - fev/2017'
import socket, threading, time, os, json, requests
from datetime import datetime
logo = '''
_ __ _ __ __ ______
| | \| |/' _/__`./ _/_ |
| | | ' |`._`.|_ | \__/ /
|_|_|\__||___/__.'\__/_/
* portscan *
'''
class tcp_... |
import requests
# def thais_func(num):
# thais_list = [num] * num
# print('thais_list', thais_list)
def get_stuff(url):
r = requests.get(url)
return r.text
stuff = get_stuff('http://www.google.com')
print(stuff)
|
import os
import sys
import subprocess
from time import sleep
from subprocess import Popen
proc = subprocess.Popen(['arecord --device=hw:1,0 --duration=10 --format S16_LE --rate 44100 -V mono -c1 test.wav'], shell=True)
sleep(10)
proc.terminate()
print("Closing the recording and wait please....")
print("Listening a... |
from django import forms
from .validators import validate_author_email
from .models import PostModel
SOME_CHOICES = [
('1','One'),
('2','Two'),
('3','Three')
]
PUBLISH_CHOICES = [
('draft','Draft'),
('publish','Publish'),
('private','Private')
]
YEARS = [ x for x in range(1980,250)]
COUNT_CHOICES = [ tuple([x,x]... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 4 08:39:55 2016
@author: ranko
"""
def closest_power(base, num):
'''
base: base of the exponential, integer > 1
num: number you want to be closest to, integer > 0
Find the integer exponent such that base**exponent is closest to num.
Note that the bas... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# passerelle-imio-ia-delib - passerelle connector to IA DELIB IMIO PRODUCTS.
# Copyright (C) 2016 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free ... |
from django.contrib import admin
# Register your models here.
from .models import Stock, DetailPage, Price
admin.site.register(Stock)
admin.site.register(DetailPage)
admin.site.register(Price)
|
#Michael Lohr
#21310937
#pytech_query.py
#6/20/21
from pymongo import MongoClient
url = "mongodb+srv://admin:admin@cluster0.2evqo.mongodb.net/students?retryWrites=true&w=majority&ssl=true&ssl_cert_reqs=CERT_NONE"
students = MongoClient(url)
db = students.pytech
collection = db.students
docs = collection.find({})
... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
import csv
class MianshiPipeline(object):
# def open_spider(self, spider):
# self.db = pymysql.conne... |
# String bisa menggunakan = " " atau ' '
Nama = "Rizki Pandiwa"
print("nama saya adalah "+Nama)
# mendefisikan string menggunkana index lokasi karakternya
nama_panggilan = Nama[6:13]
print("nama panggilan saya adalah "+nama_panggilan)
|
import os
#this file runs the entire PyFilter Project using subprocess commands to run the files
import time
starttime=time.time()
detect = "sudo python3 ./twitter_detection.py"
while True:
print('Running Detection')
os.system(detect)
print("Processed")
time.sleep(45.0 - ((time.time() - starttime) % 4... |
from pathlib import Path
class Device:
"""A Class for the state of an IntCode program"""
def __init__(self, data):
data = data.split("\n")
self.reg = dict(zip(list("abcd"), [0] * 4))
self.instr_ptr = 0
self.instrs = []
for line in data:
line = line.split(" ... |
__author__ = 'Michael May'
#http://deeplearning.net/software/theano/tutorial/examples.html
from theano.tensor.shared_randomstreams import RandomStreams
from theano import function
srng = RandomStreams(seed=234)
rv_u = srng.uniform((2,2))
rv_n = srng.normal((2,2))
f = function([], rv_u)
g = function([], rv_n, no_defa... |
import warnings
warnings.simplefilter(action='ignore', category=Warning)
from flask import Flask, render_template, request, redirect
import os
from time import sleep
import tensorflow as tf
from PIL import Image
import numpy as np
from datetime import datetime
import shelve
from glob import glob
from random import rand... |
#!/usr/bin/python3
# system-wide requirements
from flask import Flask, render_template, request
import threading
import logging
import getopt
import yaml
import sys
# local requirements
from lib.CacheManager import *
from lib.ConfigManager import *
from lib.AudioClipProcessor import *
from lib.StatsProcessor import *... |
#!/usr/bin/python3
import numpy as np
import pandas as pd
import string
import matplotlib.pyplot as plt
# 中文支持
plt.rcParams['font.sans-serif'] = ['SimHei']
# 有时间负号也不能显示
plt.rcParams['axes.unicode_minus'] = False
# 约束布局
fig, axes = plt.subplots(2, 2, constrained_layout=True)
ax1 = axes[0][0]
ax1.set_title('Title 1')... |
# ___________________________________________________________________________
#
# Prescient
# Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain rights in this software.
# This software is ... |
######################################################################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... |
{
"targets": [
{
"target_name": "main",
"sources": [ "lib/main.cpp" ],
"include_dirs" : [
"<!(node -e \"require('node-addon-api')\")"
]
}
],
} |
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def get_site_root(context):
# This returns a core.Page. The main menu needs to have the site.root_page
# defined else will return an object attribute error ('str' object has no
# attribute 'get_children')
... |
from django.shortcuts import render, redirect
# Create your views here.
from django.views.generic.base import View
from django.views.generic.base import TemplateView
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView
from d... |
from django.shortcuts import render_to_response, redirect
from django.http import HttpResponseForbidden, HttpResponse
from django.template import RequestContext #, loader, Context
from django.contrib.auth.decorators import login_required
from bowlpicks.profiles.forms import PlayerForm
from bowlpicks.profiles.models i... |
#!/usr/bin/env python3
"""Gun Tag by E1Z0
Gun Tag is like the game tag, but the chasing player
uses bullets to tag the runner player.
The runner player will get a point
for every half second they stay running.
Then winner is the player who gets 100 points first.
A tag will cause the players to switch roles,
which ... |
# coding: utf-8
from tests.lagesonum_tests import LagesonumTests
from tests.test_input_number import InputTests
from unittest import main
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.