text stringlengths 38 1.54M |
|---|
# Generated by Django 3.1.7 on 2021-04-17 16:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0003_auto_20210405_1927'),
]
operations = [
migrations.CreateModel(
name='Benchmark',
fields=[
... |
import requests
import bs4
import re
response = requests.get('https://www.federalregister.gov/articles/search?conditions%5Bpublication_date%5D%5Bis%5D=06%2F10%2F2015&conditions%5Btype%5D=NOTICE')
soup = bs4.BeautifulSoup(response.text)
data = soup.select("div.article_count h2.title_bar")[0]
print(data.text)
|
# shows audio analysis for the given track
from __future__ import print_function # (at top of module)
from spotipy.oauth2 import SpotifyClientCredentials
import json
import spotipy
import time
import sys
client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_c... |
import re,sys,os
import os.path
from parsing import interprets,ReturnValue
IsFirst = InputEnable = XMLEnable = HelpEnable = False
SourceFile = InputEnable = ""
for argument in sys.argv:
if argument=="--help":
HelpEnable = True
elif re.match('--source=.*',argument):
XMLEnable = True
... |
# !/usr/bin/env python
# -- coding: utf-8 --
# @Author zengxiaohui
# Datatime:8/10/2021 2:41 PM
# @File:DepthwiseSeparableConvolution.py
import torch
from torch import nn
class DepthwiseSeparableConvolution(nn.Module):
def __init__(self, in_ch, out_ch, kernel_size=3, stride=1, padding=1):
super().__init__... |
# -*- coding: utf-8 -*-
# @File : __init__.py.py
# @Author : AaronJny
# @Time : 2020/03/01
# @Desc :
from flask import Blueprint
main_blueprint = Blueprint('main_blueprint', __name__)
from . import views |
import smtplib
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
# Authentication
s.login("sender_mail", "your_pwd")
# message to be sent
message = "Hey Developer, you need to check your code once. The accuracy of your model is not so good."
# send... |
num = int(input("Digite um numero: "))
lista = []
if (num % 2 != 0) and (num == 2):
print("O numero é primo")
else:
for i in range(num):
if num % (i + 1) == 0:
lista.append(i + 1)
print(f"Os numeros que são divisiveis por {num} são {lista}", end=" ") |
from models.units import TO_ADD, TO_REMOVE, GAME_OBJECTS, delete_unit
from mechanics.team import TEAMS
def update(dt):
while not TO_ADD.empty():
obj = TO_ADD.get(block=False)
GAME_OBJECTS.append(obj)
TO_ADD.task_done()
while not TO_REMOVE.empty():
obj = TO_REMOVE.get(block=F... |
# Imports
import serial
import struct
import sys
import subprocess
import os
import time
import signal
import random
import re
from datetime import datetime
# Function that send command in cmd prompt
def sendCommand(input_stream, command):
print(command.decode("utf-8"))
input_stream.write(command)... |
#!/usr/bin/env python
import os, sys, subprocess
def run_and_wait(cmd):
process = subprocess.Popen(cmd, shell=True)
process.wait()
def gen_script_files(path):
return filter(lambda f: f.endswith("_generated.sh"), os.listdir(path))
for sf in gen_script_files("."):
run_and_wait("qsub " + sf)
|
from random import choice
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
small, big = ListNode(-1), ListNode(-1)
... |
import cv2
import numpy as np
img = cv2.imread('images/relation.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
cv2.imwrite('houghlinesCanny.jpg',edges)
# cv2.imshow('img', edges)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
minLineLength = 100
maxLineGap = 10
lines =... |
from setuptools import setup
setup(name="nbpaperwriter",
version="0.1.0a",
description="A tool to write interactive scientific papers as Jupyter notebooks and convert them to LaTeX files",
url="https://github.com/ilumsden/nbpaperwriter",
author="Ian Lumsden",
author_email="lumsden.ian@gma... |
class Solution:
def searchInsert(self, nums, target) -> int:
for i in range(len(nums)):
if target <= nums[0]:
return 0
break
if target > nums[-1]:
return len(nums)
break
if tar... |
from office365.runtime.client_value import ClientValue
class ListItemCollectionPosition(ClientValue):
pass
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Author : GaoYQ
# @Time : 2019/7/9 14:09
# @Software: PyCharm
import tensorflow as tf
def get_weight(shape, l2_loss_rate=None):
weights = tf.get_variable('weights', shape, initializer=tf.truncated_normal_initializer(stddev=0.1))
if l2_loss_rate is not No... |
from django.contrib import admin
from .models import Deposito
# Register your models here.
admin.site.register(Deposito)
|
def centro(matriz):
posFila=0
posCol=0
for i in range(5):
for j in range(5):
if (matriz[i][j]=='1'):
posFila=i
posCol=j
break
posiciones=abs(posFila-2)+abs(posCol-2)
return posiciones
def main():
lista=[]
for i in range(5):
lista.append(input().split(" "))
print(centro(lista))
main() |
import pandas as pd
import numpy as np
from scipy.stats import mvn,norm
BBB=[0.18,0.12,1.17,5.30,86.93,5.95,0.33,0.02]
A =[0.06,0.01,0.26,0.74,5.52,91.05,2.27,0.09]
D1=[0]
for i in BBB:
D1.append(D1[-1]+i)
D2=[0]
for i in A:
D2.append(D2[-1]+i)
ppf1=np.array([norm.ppf(i/100,0,1) for i in D1])
ppf2=np... |
#
# 백준 1316
# list(s)를 하면 문자열이 각각 리스트에 들어감
# sorted(s, key=s.find)를 사용하면 s에서 찾아지는 캐릭터 순으로 정렬
# s = happy 일 때,
# list(s) = ['h', 'a', 'p', 'p', 'y']
# sorted(s, key=s.find) = ['h', 'a', 'p', 'p', 'y']
count = 0
for _ in range(int(input())):
s = input()
if list(s) == sorted(s, key=s.find):
count += 1
pr... |
import dgl
import torch
'''
create the graph network, possibly create the sharing functions here as well so in the next step can just pass on
requested word vectors, don't know about this though because of how parameter updating works, may be better just to pass
on the graph network
'''
def build_graph(edge... |
import socket
import os
UDP_IP = "192.168.100.151"
UDP_PORT = 53
sock = socket.socket(socket.AF_INET,
socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024)
packet = str(data[0]) + str(data[1]) + b"\x81\x80" + os.urandom(128)
sock.s... |
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from django.urls import reverse
import random
# Create your models here.
class Match(models.Model):
name = models.CharField(max_length=100,default=None)
judge = models.ForeignKey(User, on_delete=models.CAS... |
from dataclasses import dataclass
@dataclass
class Settings:
material_mode: str = 'pbr'
physics_engine: str = 'builtin'
blender_dir: str = ''
blender_bin: str = 'blender'
append_ext: bool = False
pipeline: str = 'gltf'
no_srgb: bool = False
textures: str = 'ref'
animations: str = 'e... |
import random
import math
import sys
import os
from BBS import BlumBlumShub
from BBS import millerRabin
######## HELPER CLASSES ########
class public_key(object):
def __init__(self, group_n = None, prim_root = None, prim_rt_exp_priv = None, num_bits = 0):
self.group_n = group_n
self.prim_root = prim_root
self... |
from django import forms
from dataset.models import Dataset
class DatasetForm(forms.Form):
#dataset_choices = [('test','test')]+[(dataset.title, dataset.title) for dataset in Dataset.objects.all()]
#dataset = forms.ChoiceField(choices=dataset_choices, widget=forms.Select(attrs={'id':'select_dataset','name':'s... |
# Generated by Django 2.0.6 on 2018-07-03 06:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mainApp', '0004_auto_20180703_1153'),
]
operations = [
migrations.RenameField(
model_name='authtoken',
old_name='refresh_tok... |
# Задание - 1:
# Напишите функцию, округляющую полученное произвольное десятичное число
# до кол-ва знаков (кол-во знаков передается вторым аргументом)
# Округление должно происходить по математическим правилам (0.6 --> 1, 0.4 --> 0).
# Для решения задачи не используйте встроенные функции и функции из модул... |
import getopt
import sys
texto = "Eu/PROPESS nunca/ADV almoço/V à/PREP+ART hora/N do/KS almoço/N Eu/BATATAS Eu/PROPESS almoço/batatinhas"
def words_tag(texto):
occur = {}
texto = texto.split()
result = []
for palavra_anotada in texto:
palavra_anotada = palavra_anotada.split('/')
palavr... |
import numpy
import cv2
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
cv2.imshow('frame', frame)
#make red channel
r = frame.copy()
#erase other colours
r[:, :, 0] = 0
r[:, :, 1] = 0
#Show red channel
cv2.imshow('RED', r)
#make green channel
g = frame.copy()
#erase other colours fro... |
from bs4 import BeautifulSoup
import requests
import json
url = 'https://www.alexa.com/topsites/countries'
r = requests.get(url)
res = {}
soup = BeautifulSoup(r.text, 'html.parser')
for span in soup.find_all(class_='countries span3'):
for li in span.find_all('li'):
res[li.find('a').string] = li.find('a').... |
class Node:
def __init__(self, val = None):
self.val = val
self.left = None
self.right = None
class Tree:
def __init__(self, root):
self.root = Node(root)
def ancestors(self, root, nodeVal, list1 = []):
if root is None:
return
list1.append(root.val)
#print(list1)
if root.val == nodeVal:
#p... |
import os
import datetime
from flask import (
Flask, flash, render_template,
redirect, request, session, url_for)
from flask_mail import Mail, Message
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
if os.path.exists("env.py"):
import env
app = Flask(__name__)
app.config["MONGO_DBNAM... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 9 13:05:20 2014
@author: ivan
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
url = "http://donnees.ville.montreal.qc.ca/storage/f/2014-01-20T20%3A48%3A50.296Z/2013.csv"
df = pd.read_csv(url, index_col='Date', parse_dates=T... |
# The main entry point of workflow.
# After configuring, running snakemake -n in a clone of this repository should successfully execute a dry-run of the workflow.
include: "rules/common.smk"
include: "rules/ref.smk"
include: "rules/qc.smk"
include: "rules/cutadapt.smk"
include: "rules/mapping.smk"
include: "rules/filt... |
import string
import csv
import copy
import math
import time
# Method that trains on data
def train_emmision_transition(filename):
# Variables
tags = {}
transition = {}
alltags = []
allwords = []
# Opens Training Data
with open(filename, 'r') as trainingobj:
traindata = csv.reader(t... |
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-10-21 19:11
import os
from typing import Union, List, Callable, Dict, Iterable
from hanlp.datasets.tokenization.loaders.txt import TextTokenizingDataset
from hanlp.utils.io_util import get_resource
class MultiCriteriaTextTokenizingDataset(TextTokenizingDataset):
... |
#!/usr/bin/env python3
"""
Download Conference Addresses for the apostles from churchofjesuschrist.org
"""
__author__ = "Greg Reeve"
__version__ = "0.1.0"
__license__ = "MIT"
import argparse
import os
import re
import requests
from bs4 import BeautifulSoup
from logger import setup_logger
logger = setup_logger(logf... |
import sys
sys.path.append("..")
import unittest
from app.Decryptor.basicEncryption.caesar import Caesar
from languageCheckerMod.languageChecker import LanguageChecker
# python3 -m unittest Tests.testchi_squared
# python -m unittest discover -s tests
# python3 -m unittest discover -s Tests -p test*.py
# {"lc"... |
# 4. Реализовать простую систему хранения данных о суммах продаж булочной. Должно быть два скрипта с интерфейсом командной строки: для записи данных и для вывода на экран записанных данных.
# Данные хранить в файле bakery.csv в кодировке utf-8.
# При записи передавать из командной строки значение суммы продаж. Новая ... |
n=int(input("Enter n"))
def isprime(n):
return(factors(n)==[1,n])
def factors(n):
flist=[]
for i in range(1,n+1):
if (n%i == 0):
flist=flist+[i]
# print(flist)
return(flist)
prime=isprime(n)
if (prime == True):
print("n is prime")
else:
print("n is not prime")
|
# def sum_many(*args):
# sum = 0
# for i in args:
# sum = sum + i
# return sum
# print(sum_many(1,2,3))
def average(*args):
result = 0
for i in args:
result += i
return result / len(args)
print(average(22,55,8,885)) |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 9 19:45:58 2020
@author: Hugo
"""
import math
#Picard Peano
f = lambda x : math.e**x-4*x**2
g = lambda x : 2*math.log(2*x)
def picardPeano(x):
x = g(x)
return x
x=1.1
print(x)
print(picardPeano(x))
print(g(x)-x)
|
"""Create and configure the Dash App."""
import dash
import dash_bootstrap_components as dbc
import dash_html_components as html
import pandas as pd
from dash.dependencies import Input, Output
import covid19.data
app = dash.Dash(
external_stylesheets=[dbc.themes.CERULEAN],
meta_tags=[{"name": "viewport", "con... |
def read_int_list():
return list(map(int, input().split()))
def read_ints():
return map(int, input().split())
def main():
N, X = read_ints()
amount = 0
for i in range(N):
V, P = read_ints()
# print(V * (P / 100))
amount += V * P
# print(amount)
if amount ... |
import random
import arcade
class Ground(arcade.Sprite):
def __init__(self):
super().__init__()
# self.walk_left_textures = [arcade.load_texture("image\g0.png"),
# arcade.load_texture("image\g1.png"),
# arcade.load_text... |
#!/usr/bin/env python
from flask import Blueprint, request, url_for, redirect
from flask import render_template, current_app
from corpint.integrate import train_judgement
blueprint = Blueprint('base', __name__)
SKIP_FIELDS = ['name', 'origin', 'fingerprint', 'uid']
JUDGEMENTS = {
'TRUE': True,
'FALSE': False... |
#!/remote/us01home40/phyan/depot/Python-2.7.11/bin/python
from qor_web import app
import unittest
import urllib2
import json
# from flask.ext.testing import TestCase
from flask_testing import TestCase, LiveServerTestCase
import unittest
import flask
# from flask import Flask, url_for
from selenium import webdriver
from... |
# Numbers can be stored in variables
pi = 3.141592
print(pi)
first_num = 5
second_num = 3
print(first_num + second_num)
print(first_num ** second_num)
# Combine numbers and string
days_in_feb = 28
# print(days_in_feb + " days in Febraury")
# When displaying a string that contains numbers you must convert the numbers... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy import Request
import urlparse
from urlparse import urljoin
#from urllib.parse import urljoin
class SpiderSpider(scrapy.Spider):
name = 'new'
allowed_domains = ['www.avvo.com/all-lawyers/ny/new_york']
start_urls = ['http://www.avvo.com/all-lawyers/ny/new_... |
from datetime import datetime
from sqlalchemy.dialects.postgresql import insert
from app import db
from app.dao.dao_utils import autocommit
from app.models import DailySortedLetter
def dao_get_daily_sorted_letter_by_billing_day(billing_day):
return DailySortedLetter.query.filter_by(billing_day=billing_day).firs... |
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans, AgglomerativeClustering, AffinityPropagation
from sklearn.datasets import load_digits
from sklearn.metrics import confusion_matrix, fowlkes_mallows_score
from sklearn.model_selection import train_test_split
from sklearn.utils.multicl... |
"""
Exercício Python 042: Refaça o DESAFIO 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será
formado:
- EQUILÁTERO: todos os lados iguais
"""
a, b, c = map(float, input('Informe os três lados do triângulo: ').split())
if a > b + c or b > a + c or c > a + b:
print('Os lados informados... |
#Dragging a window
import pygame
pygame.init()
#Variables
x1=400
y1=400
window = pygame.display.set_mode([x1, y1])
drawing=True
border=False
a=0
##When you press the mouse at the border and the window updates,
##the computer thinks after the update that the mousebutton has just gone up.
##Thus, change_w... |
# -*- encoding: utf-8 -*-
import logging
import traceback
import MySQLdb as mysql
from DBUtils.PooledDB import PooledDB
class Cursor():
def __init__(self, config):
self.config = dict([(k[6:], config[k]) for k in config if k.startswith('mysql_')])
if 'port' in self.config:
self.config['p... |
#!/usr/bin/env python3
import pickle
import click
import os
import sys
from datetime import datetime, timedelta
import dateutil.parser
import ansiwrap
from config import *
from utils import *
base_path = os.path.abspath(os.path.split(__file__)[0])
os.chdir(base_path)
today = datetime.now().strftime("%Y-%m-%d")
try:
... |
import plane_factory
import flywight
import button
import abc
class Level:
__metaclass__= abc.ABCMeta #抽象类
def changeLevel():
pass
def done(self):
pass
class Level_1(Level, button.ButtonListener):
def __init__(self, enemy_plane, bg_size):
Level.__init__(self)
... |
from datetime import datetime, timedelta
from typing import Optional
from uuid import UUID
import oasst_backend.models.db_payload as db_payload
from loguru import logger
from oasst_backend.config import settings
from oasst_backend.models import ApiClient, Task
from oasst_backend.models.payload_column_type import Paylo... |
#!/bin/python3
import sys
import string
SEPARATOR = ' '
LETTER_WIDTH = 1
heights = [int(h_temp) for h_temp in input().strip().split(SEPARATOR)]
word = input().strip()
width = len(word) * LETTER_WIDTH
height = max(heights[ord(letter) - ord('a' if letter.islower() else 'A')] for letter in word)
area = wi... |
# Generated by Django 3.0.4 on 2020-07-08 08:45
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('user', '0006_user_isagency'),
('api', '0055_auto_20200703_0458'),
]
operations = [
migrations.Creat... |
text = input("Enter your message: ")
shift=int(input('Number of shifting:'))
cipher = ''
for char in text:
if ord(char) in range(65,91):
if ord(char)+shift >90:
code = ((ord(char)+shift)-90)+64
else:
code = ord(char) + shift
elif ord(char) in range(97,123):
... |
import logging
import sys
if sys.version_info < (2, 7):
from ordereddict import OrderedDict
else:
from collections import OrderedDict
from django.views.generic.detail import BaseDetailView
from django.views.generic.edit import BaseCreateView, BaseUpdateView,\
ProcessFormVi... |
class XmlError(Exception):
pass
class FmError(Exception):
def __init__(self, msg="", code=-1, version='fms17'):
self._msg = msg
self.code = code
self.version = version
super().__init__("taaasdf")
def __str__(self):
msg = self._msg
if not self._msg:
... |
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from WorldCup import *
class MainWindow(QMainWindow):
""" This is the class for the main window of the world cup python statistics api"""
def __init__(self):
super().__init__()
self.resize(400,400)
self.setWindowTitle("PyCup Statistics")
... |
"""
A subpackage hosting Numba IR rewrite passes.
"""
from .registry import register_rewrite, rewrite_registry, Rewrite
# Register various built-in rewrite passes
from numba.core.rewrites import (static_getitem, static_raise, static_binop,
ir_print)
|
"""
The yaaredis integration traces yaaredis requests.
Enabling
~~~~~~~~
The yaaredis integration is enabled automatically when using
:ref:`ddtrace-run<ddtracerun>` or :ref:`patch_all()<patch_all>`.
Or use :ref:`patch()<patch>` to manually enable the integration::
from ddtrace import patch
patch(yaaredis=T... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 23 20:01:31 2016
@author: yangyi05
"""
import os
import io
import logging
logging.getLogger().setLevel(logging.INFO)
class Html(object):
def __init__(self, config):
self.url_file = os.path.join(config.data_dir, 'url.txt')
self.test_data_file = confi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Look at the strokes, select the best and make a core out of them'''
import json
import sys
from os.path import join
from os import rename
from core_creator import make_core, get_letters
from PyQt4.QtCore import QAbstractListModel
from PyQt4.QtCore import Qt
from PyQt4... |
import ipaddress
import json
import pathlib
import shutil
import tempfile
import unittest
import httpretty
from freenom_dns_updater import EncryptedString
class EncryptTringTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_encrypt(self):
with Enc... |
#!/usr/bin/python -tt
import networkx as nx
import numpy as np
import sys
import random as rd
import matplotlib.axes as ax
import matplotlib.pyplot as plt
n = int(sys.argv[1])
p = float(sys.argv[2])
phi = float(sys.argv[3])
sigma = float(sys.argv[4])
G = nx.Graph()
G.add_nodes_from(range(n))
node_Phi = np.array(np.... |
# -*- coding: utf-8 -*-
"""Django application to manage some datas about Emencia client websites"""
__version__ = '0.3.4'
|
from HTMLParser import HTMLParser
import parsers
from parsers import HTMLParserTag
from parsers import HTMLParserTagWithAttribute
from parsers import HTMLParserBetweenTags
from collections import namedtuple
import urllib, urllib2, logging, locale
Torrent = namedtuple("Torrent", "filename url magnet torrentFile torrent... |
class PositionalArgumentsError(Exception):
def __init__(self, f, n, message=None):
super(PositionalArgumentsError, self).__init__()
self.f = f
self.n = n
self.message = message
def __str__(self):
if self.n == 0:
return "%s takes only keyword arguments" % self... |
"""
subscribe.py
Subscribe to TACC apis
"""
import requests
from ..constants import PLATFORM
from ..utils import (handle_bad_response_status_code, prompt_username,
prompt_password)
from .exceptions import AgaveClientError
from .utils import clients_url
def clients_subscribe(client_name,
... |
# -*- coding: Latin-1 -*-
# Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See License.txt for complete terms.
# IMAGE_DATA_DIRECTORY_ -> CybOX Windows Executable File Object Data Directory DataDirectoryStruct mappings
"""Represents an array of data directory structures containing the RVA and size o... |
import sys
import argparse
import numpy as np
import cv2
import copy
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle, Circle
import h5py
import os
import pycocotools._mask as _mask
import pycocotools.mask as cocoMask
i... |
# [ <expression> for <element> in <iterable> if <condition> ]
squares = [ x*x for x in (1,2,3,4) ]
print(squares)
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
a = (x for x in range(10) if x % 2 == 0)
print(a)
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayEbppBillchargeSuborderQueryModel(object):
def __init__(self):
self._open_id = None
self._order_no = None
self._source = None
self._sub_order_no = None
... |
# from django.contrib.auth.forms import AuthenticationForm
from django.shortcuts import render, redirect
from .forms import UserRegisterForm, UserLoginForm
from django.contrib import messages
from django.contrib.auth import (
authenticate,
get_user_model,
login,
logout,
)
# login functionality
def lo... |
# import packages
import numpy as np
import matplotlib.pyplot as plt
import collections
np.set_printoptions(threshold=np.nan)
# plt(x, y) # plot x and y using default line style and color
# plt(x, y, 'bo') # plot x and y using blue circle markers
# plt(y) # plot y using x as index array ... |
#!/usr/bin/env python
#
# Copyright (c) 2009 Martin Matusiak <numerodix@gmail.com>
# Licensed under the GNU Public License, version 3.
#
# Runs sample testing on solarbeam vs reference code, yielding mean, max and
# standard deviation.
import math
import os
import os.path
import random
import re
import subprocess
impo... |
import logging
import sys
import unittest
from pysecm.ric import RIC
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
class InstrumentTests(unittest.TestCase):
def test_from_rics(self):
rics = ['RY.TO', 'RY_pa.TO', 'USDCAD', '.VIX', 'CLc1', 'SIZ0', 'NG', 'UST BILL 03-DEC-2020',
... |
from rest_framework import serializers
from .models import Movie, Actor
class MovieSerializer(serializers.ModelSerializer):
# omdb_details = serializers.CharField(read_only=True)
class Meta:
model = Movie
fields = ('movie_id', 'title_type', 'primary_title', 'original_title', 'is_adult', 'star... |
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
# 2021.03.11
# 1st: naive solution:
lim = 2**31
x_sign = 1 if x < 0 else 0 # deal with the negative sign
r_str = '-' if x < 0 else ''
for c in rever... |
__author__ = 'Ice'
# -*- coding: utf-8 -*-
import re
import threading
import Constants
import Utils
lock = threading.RLock()
zhuansheng_lock = True
jiadian_lock = True
def getUserInfo(ID):
return "merrymin", "861560"
class Game(object):
def __init__(self, username, password):
if not username and n... |
from django.shortcuts import render
from testapp.models import Employee
# Create your views here.
def retrieve_view(request):
employees=Employee.objects.all()
return render(request,'testapp/home.html',{'employees':employees})
def create_view(request):
form=EmployeeForm()
if request.method=='POST':
... |
from sympy import*
x = Symbol('x')
y = Symbol('y')
try:
limit = int(input("limit>>"))
except:
limit = 10000
g = sympify(input("f>>"))
print("\n[f="+str(g)+"]\n\n<<LIMITED["+str(limit)+"]>>\n\n__start__")
counter = 0
while True:
g = diff(g,x)
counter += 1
result = "["+str(counter)+"]"+str(expand(g... |
from bs4 import BeautifulSoup
from urllib2 import urlopen
from sys import argv
from os import makedirs, chdir
from re import sub, search
from datetime import datetime
def download_img(id):
base_url = 'http://www.sporthoj.com/galleri/bild?id={0}&header=1'
img = urlopen(base_url.format(id))
with open(id + '.jpg',... |
"""
Created on May 1, 2013
@author: Guillaume Bouvignies
"""
parse_line = "15N - Coupled Nitrogen CEST"
description = """\
Analyzes 15N chemical exchange in a uniformly 13C-labeled sample in the presence
of 1H composite decoupling during the CEST block. This keeps the spin system
only coupled to the neighbouring ca... |
from flask import Flask, redirect, url_for, render_template, request
app=Flask(__name__)
@app.route("/")
def home():
return render_template("index.html")
@app.route('/contact', methods=['GET', 'POST'])
def contact():
if request.method == 'GET':
print("We received GET")
return render_template("f... |
from __future__ import absolute_import, division, print_function, unicode_literals
from six import BytesIO
from ._formats import ImageFormat
from ._typeformatting import format_tile_dimensions
class Tile(object):
def __init__(self, coordinates, indices, tile_shape=None, sha256=None, extras=None):
self.c... |
from collections import Iterable
def mymap(func, args):
"""
>>> plus1 = lambda x: x+1
>>> minus1 = lambda x: x-1
>>> mymap(plus1, 1)
[2]
>>> mymap(plus1, [1,3])
[(2, 4)]
>>> mymap([plus1, minus1], [1,2])
[(2, 3), (0, 1)]
"""
if not isinstance(func, Iterable):
func =... |
import dash
import pandas as pd
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input,Output,State
import plotly.graph_objs
from iexfinance.stocks import get_historical_data as gst
from datetime import datetime
options=[]
cl=pd.read_csv('NASDAQcompanylis... |
#!/usr/bin/env python
# 1. Basic image capturing and displaying using the camera module
import pygame
import pygame.camera
from pygame.locals import *
red=(255,0,0,255)
blue=(0,0,255,255)
black=(0,0,0,255)
xposi=0
yposi=0
class VideoCapturePlayer(object):
size = ( 160, 120 )
screensize=(640,480)
frames=0
... |
import cv2
import numpy as np
from skimage import morphology
import cPickle
from matplotlib import pyplot as plt
import hashlib
import string
import random
from pysimplesoap.client import SoapClient
import time
def improveImage(wImage):
img = cv2.imread(wImage)
gray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
... |
#!/usr/bin/python3
import pandas as pd
import numpy as np
import requests, sys
from itertools import combinations
#import seaborn as sns
from scipy import stats
import pickle
from collections import Counter
import copy
from scipy.stats import sem, t
from scipy import mean
import re
import os
import gzip
import time
... |
from __future__ import absolute_import
from abc import ABCMeta, abstractmethod
from six.moves import range
import torch
from torch.autograd import Variable
from torch.nn.functional import relu
from .base import Struct
def tensor_to_string(tensor):
"""
Formats a torch.FloatTensor as a string.
:type ten... |
#!/usr/bin/env python3.6
import lnd.rpc_pb2 as ln
import lnd.rpc_pb2_grpc as lnrpc
#import btcwallet.api_pb2 as btcw
#import btcwallet.api_pb2_grpc as btcwrpc
#import requests
import jsonrpc_requests
import grpc
import os
import time
from retrying import retry
class BitCuddle:
def go(self):
print("Hello... |
import numpy as np
from vis_support.markers import Markers
from core.truncated import is_truncated
def setup_data_source(mainwindow, filename):
# get length of data and whether it has previously been truncated
num_points, offset = is_truncated(mainwindow.pycgm_data)
# marker source
# ensure we have u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.