text stringlengths 8 6.05M |
|---|
print "importing matplotlib"
import matplotlib.pyplot as plt
print "done importing matplotlib"
import autograd.numpy.linalg as npla
import autograd.numpy as np
import autograd.numpy.random as npr
import autograd.scipy.misc as scpm
from autograd import grad
import tractor.sdss as sdss
import astrometry.sd... |
from pymongo import MongoClient
symbol_list = ['ethusdt', 'btcusdt', 'bchusdt', 'ltcusdt', 'eosusdt', 'ethbtc', 'eosbtc', 'xrpusdt']
period = ['1min', '5min', '15min', '30min', '60min', '4hour', '1day', '1week', '1mon']
orders_list = ['submitted', 'partial-filled', 'partial-canceled', 'filled', 'canceled']
mdb = {
... |
import pytest
from pages import LoginPage,MenuPage,Role_management
from utils.db import AddRoleDB
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
@pytest.fixture(scope='session')
def selenium(chrome_opti... |
sentence = input()
s, t = sentence.split()
j = 0
word = ''
for i in range(len(t)):
if t[i] == s[j]:
word += t[i]
j += 1
if j==len(s):
break
if s in word:
print("Yes")
else:
print("No")
|
import requests
import psycopg2
conn = psycopg2.connect(host="localhost", database="cartola_fc",
user="postgres", password="postgres")
print("Conectado ao banco")
cur = conn.cursor()
rowcount = cur.rowcount
url = "https://api.cartolafc.globo.com/atletas/mercado"
try:
data = requests.get(url).json()
pri... |
#import sys
#input = sys.stdin.readline
def main():
K = int( input())
now = 7
now %= K
for i in range(10**7):
if now == 0:
print(i+1)
return
now = (now*10+7)%K
print("-1")
if __name__ == '__main__':
main()
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Title :test4.py
# Description :I am test script
# Author :Devon
# Date :2018-01-04
# Version :0.1
# Usage :python test4.py
# Notes :
# python_version :2.7.14
# ======================================================... |
# 144. Binary Tree Preorder Traversal
#
# Given a binary tree, return the preorder traversal of its nodes' values.
#
# For example:
# Given binary tree [1,null,2,3],
# 1
# \
# 2
# /
# 3
# return [1,2,3].
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
... |
# Lint143. Sort Colors II
'''
Given an array of n objects with k different colors (numbered from 1 to k), sort them so that objects of the same color are adjacent, with the colors in the order 1, 2, ... k.
'''
Solution 1: Counting Sort (Naive)
Time O(n) Space O(k)
Solution 2: Quick Sort idea (preferred)
Time O(nl... |
#Programa: intercambio.py
#Propósito: Intercambiar el valor de dos variables númericas
#Autor: Jose Manuel Serrano Palomo.
#Fecha: 13/10/2019
#
#Variables a usar:
# A,B los dos números a los que vamos a intercambiar
# suma nos ayudará a realizar el intercambio
#Algoritmo:
# LEER A,B
# suma <-- A + B
# A <-- suma - A
# ... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
'''
Created on 2017/12/18
@author: ChaoZhong
@email: 16796679@qq.com
'''
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, SelectField
from wtforms.validators import DataRequired, Length, IPAddress
from .models import Category
cl... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 14:49:57 2019
@author: saib
"""
urls = ['a.in','b.hk','c.in','h.in','k.uk','us.com']
print(list(filter(lambda x : x.endswith('in'),urls)))
|
import pygame
import random
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((640, 640))
# player
playerX_change = 20
playerY_change = 20
pos_X = random.randint(0, 32) * 20
pos_Y = random.randint(0, 32) * 20
player_surface = pygame.transform.scale(pygame.image.load("player.png"... |
from app.controllers.auth import auth
from app.libraries.response_message import error_message, data_message
from app.database import session
from app.models.category import Category
from app.models.course import Course
from flask import (
Blueprint,
request,
)
page = Blueprint('course', __name__, static_fold... |
import platform
import re
from collections import namedtuple
from copy import deepcopy
from elasticsearch.helpers import streaming_bulk
from elasticsearch.exceptions import NotFoundError
from langdetect.lang_detect_exception import LangDetectException
from onegov.core.utils import is_non_string_iterable
from onegov.se... |
#!/usr/bin/python
#!/usr/bin/env python
#simple script to look for and download videos from YT, parameters are provided via arguments, you can select the video acording to size,format
#resolution etc. I have to add an option to download audio only. And have to polish up the code a little bit, its 5:52 am and the holid... |
from django.db import models
from datetime import datetime as dt
# Create your models here.
class ContactUs(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField()
comment = models.TextField()
comment_date = models.DateTimeField(auto_now_add=dt.now)
def __str__(self):
... |
from astropy.table import Table, Column
import numpy as np
import astropy.table
import sys
import glob
KEEP = "w ns omegam sigma8 H0 omegabh2 omeganuh2".split()
def add_extra_parameters(cat):
"""
Add additional DES systematics to the Planck chain. Since the data
doesn't constrain these at all just draw from a ... |
from flask import Flask, render_template, Response
import cv2
import time
# import camera
app = Flask(__name__)
# cam = camera.camera('rtsp://admin:QPPZFE@192.168.100.57:554/H.264_stream')
# cam = cv2.VideoCapture('rtsp://admin:QPPZFE@192.168.100.57:554/H.264_stream') # use 0 for web camera
# for cctv camera use rts... |
from keras.callbacks import Callback
class ClassAccuracy(Callback):
def __init__(self, data_x, data_y, class_label, label="class accuracy"):
super(ClassAccuracy, self).__init__()
self.label = "%s for %s" % (label, class_label)
self.class_label = class_label
self.data_x = data_x
... |
from rec2 import factorial as fact
import rec2
print(fact(4))
print(rec2.factorial(2))
|
from slack_webhook import Slack
URL=''
def send_slack(msg):
slack = Slack(url=URL)
slack.post(text=msg)
|
from models import Session, FoodieUser
s = Session()
def create_users():
s.add(FoodieUser(name='John Doe', age=44))
s.add(FoodieUser(name='San Martin', age=999))
s.commit()
def main():
create_users()
if __name__ == '__main__':
main()
|
from __future__ import absolute_import, unicode_literals
import errno
import logging
import os
import signal
import subprocess
from mopidy import backend, exceptions
import pykka
from . import Extension
from .client import dLeynaClient
from .library import dLeynaLibraryProvider
from .playback import dLeynaPlaybackP... |
#from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
import env
class Command(BaseCommand):
help = 'Delete environment in %s' % env.path
def handle(self, **options):
env.delete()
|
import ev3dev.ev3 as ev3
import ev3dev.core as core
import time as time
def main():
LEFT =ev3.Leds.LEFT
RIGHT =ev3.Leds.RIGHT
GREEN =ev3.Leds.GREEN
RED =ev3.Leds.RED
buttons =ev3.Button
ev3.Leds.all_off()
while(True):
'''core.Screen.clear()
core.Scr... |
#!/usr/bin/python
# vim: set fileencoding=UTF-8
a = int(input("? "))
b = int(input("? "))
c = int(input("? "))
if a < 1 or b < 1 or c < 1 :
print("As dimensões dos lados do triângulo devem ser todas positivas")
else:
if a + b <= c or a + c <= b or c + b <= a :
print("Não é triângulo")
else:
if a == b and ... |
from django.urls import path
from django.contrib import admin
from . import views
urlpatterns = [
path('', views.HomePage),
path('subject/', views.SubjectPage),
path('results/', views.result1),
]
|
from setuptools import setup, find_packages
setup(
name='ships',
version='1.0',
author='akerlay',
packages=find_packages(),
python_requires='>=3.7',
classifiers=[
'Environment :: Console',
'Operating System :: POSIX',
'Operating System :: Unix',
'Programming Lang... |
# # # # Processing Pipeline for the Full Domain (Artic-wide)
import subprocess, os, warnings
import xarray as xr
os.chdir('/workspace/UA/malindgren/repos/seaice_noaa_indicators/pipeline')
base_path = '/workspace/Shared/Tech_Projects/SeaIce_NOAA_Indicators/project_data/nsidc_0051'
ncpus = str(64)
# interpolate and smo... |
import multiprocessing
from gensim.models import Word2Vec
from gensim.models.word2vec import LineSentence
from sklearn.linear_model import SGDClassifier
lr = SGDClassifier(loss='log', penalty = 'l1')
# X_data = []
# Y_data = []
#
# for line in open(r"C:\Users\10651\Desktop\评论数据\200000条总数据\好样本\a.txt","r",encoding='UTF... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 22 11:50:29 2019
@author: flau
"""
import numpy as np
from scipy.io import wavfile
from scipy.signal import deconvolve
import matplotlib.pyplot as plt
fs, measure = wavfile.read('Messung.wav')
fs, test = wavfile.read('Testsignal.wav')
difference=le... |
class Dog:
count = []
def __init__(self, name, type):
self.name = name
self.type = type
self.nomer = len(self.count)
self.count.append(1)
# def add_trick(self, trick):
# self.tricks.append(trick)
dog1 = Dog("Sharik", "Alabai")
dog1.temperature = 10
# print(dog1.tem... |
import scipy.io as sio
import h5py
def load_deep_features(data_name):
import numpy as np
valid_data, req_rec, b_wv_matrix = True, True, True
unlabels, zero_shot, doc2vec, split = False, False, False, False
if data_name.find('_doc2vec') > -1:
doc2vec = True
req_rec, b_wv_matrix = False, ... |
import pathlib
import numpy as np
class ConstantRegressor:
def fit(self, X, y, eval_data=None, mlflow_log=True):
self.mean = y.mean()
def predict(self, X):
return np.ones(X.shape[0]) * self.mean
def save(self, path: pathlib.Path):
pass
@staticmethod
def load(path: pathl... |
from skimage import data
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from PIL import Image
image = mpimg.imread("1.tif")
plt.imshow(image)
plt.show() |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
def easy(url_str):
import re
pattern = re.compile(r':\w+/?')
matches = pattern.findall(url_str)
for match in matches:
var = match[1:-1]
var_re = r'(?P<%s>.*)/'%var
url_str... |
#!/usr/bin/env python3
import socket
import sys
HOST = sys.argv[1]
PORT = int(sys.argv[2])
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
txt=input()
s.sendall(txt.encode())
data = s.recv(1024)
#print("Received:", repr(data), "\n")
print(data.decode(... |
# compatibility with python 2/3
try:
basestring
except NameError:
basestring = str
class ExpressionNotFoundError(Exception):
"""Expression not found error."""
class ExpressionEvaluator(object):
"""
Runs exressions used by templates.
"""
__registered = {}
@staticmethod
def registe... |
import csv
import tweepy
from tweepy import OAuthHandler
consumer_key = ' '
consumer_secret = ' '
access_token = ' '
access_secret = ' '
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth,wait_on_rate_limit=True,wait_on_rate_limit_notify=True)
|
from topology import *
from util import *
def make_ini(T, network_name, sim_time, out_f):
with open(out_f, 'w') as of:
print("[General]", file=of)
print("network = {}".format(network_name), file=of)
print("record-eventlog = false", file=of)
print("result-dir = results_strict_priorit... |
import os
import pymongo
import logging
from flask import Flask
from flask_cors import CORS
from .jinjia_filters import JJFilters
from flask_login import LoginManager
from flask_wtf.csrf import CSRFProtect
from logging.handlers import WatchedFileHandler
app = Flask(__name__)
CORS(app)
csrf = CSRFProtect(app)
app.confi... |
from bs4 import BeautifulSoup
import requests
response = requests.get("https://www.empireonline.com/movies/features/best-movies-2/")
movie_webpage = (response.text)
soup = BeautifulSoup(movie_webpage, "html.parser")
# print(soup)
title_tags = soup.find_all(name="h3", class_="title")
all_titles = [title.text for title ... |
# coding=utf-8
import requests;
from login.Login import *;
if __name__ == "__main__":
login = Login()
login.login(email='', password='')
|
#This will take the training data in libsvm format and predict ham or spam on the basis of symbols
#using optimized Adaboost Classifier.
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from collections import Counter
X_train, y_train = load_svmlight_file('Trainlabels.t... |
import main_module
main_module.main()
print("Second modules name: {}".format(__name__))
|
#makes input cfi files for all beamspot scenarios!
import os, sys
eospath = "/eos/uscms/store/user/skaplan/noreplica/"
shortpath = "/store/user/skaplan/noreplica/"
for phi in (0,225):
for r in range(11):
if (phi == 225 and r == 0):
continue
folder="MinBiasBeamSpotPhi%iR%i_HISTATS/"%(phi,r)
fullpath = eospa... |
from bs4.dammit import EntitySubstitution
esub = EntitySubstitution()
def sanitize_html(title):
return esub.substitute_html(title)
def sanitize_irc(title):
badchars = "\r\n\x01"
return "".join(c for c in title if c not in badchars)
escapers = {
"html": sanitize_html,
"irc": sanitize_irc
}
def escape(title, mod... |
'''
This code is intended to serve as a basic example for a pendulum disturbed by a trolley
'''
import warnings
warnings.simplefilter("ignore", UserWarning)
# import all appropriate modules
import numpy as np
from scipy.integrate import odeint
import Generate_Plots as genplt
import InputShaping as shaping
import pdb
... |
#import sys
#input = sys.stdin.readline
def solve():
L, R = map(int,input().split())
if L == 0:
return (R+1)*(R+2)//2
elif R < L*2:
return 0
else:
return (R-L*2+1)*(R-L*2+2)//2
def main():
T = int( input())
ANS = [ solve() for _ in range(T)]
print("\n".join(map(str,... |
# Write a python script that will do the following. Rename all files in this folder to abide by a naming convention of data_
## where ## is an arbitrary number used to define orderering.
#You can use the following methods from the os module.
# `os.getcwd()`
# this will return the path to the current directory pytho... |
"""
===----Config------------------------------------------------------------------------===
Airbnb Clone Project, config file.
Isolating environments in Python: Development/Production/Test.
===----------------------------------------------------------------------------------===
"""
from os import environ
ENV = en... |
# coding: utf-8
from django.contrib import admin
from models import ApiToken, SpotifyUser
class ApiTokenAdmin(admin.ModelAdmin):
list_display = ("token", "date_added", "is_active")
search_fields = ["token", ]
list_filter = ("is_active", )
class SpotifyUserAdmin(admin.ModelAdmin):
list_display = ("u... |
from pipeline import Pipeline
import argparse
import os
if __name__== "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-s","--sourcePath", help = "Destination for the input folder")
parser.add_argument("-d","--destinationPath", help = "Destination for the output folder")
... |
# coding: utf-8
"""Module that contains all user repository Data Scraping logic."""
import requests
from .utils import BaseRequest
from .exceptions import (InvalidTokenError, RepositoryNameNotFoundError,
ApiError, RepositoryIdNotFoundError, ApiRateLimitError)
class RepositoryApi(BaseRequest)... |
import os
import json
from shapely.geometry import Polygon
from OSMPythonTools.api import Api
import pandas as pd
from shapely.geometry import Polygon
import copy
import cv2
import math
import shapely.geometry as geom
'''
Cretes COCO Annotation using VIA annotation
Example VIA annotation format:
{
"FLAT.213253160... |
import numpy as np
import math
from scipy.spatial import ConvexHull
# "Cross" product as used in UBC-ACM
def cross(p1, p2):
return p1[0] * p2[1] - p1[1] * p2[0]
# Euclidean distance between two points
def point_distance(p1, p2):
return np.linalg.norm(p1-p2)
# Return the rotation of point A around P (default [0... |
from flask import Flask, redirect, url_for
app = Flask(__name__)
from app.controllers import auth
app.register_blueprint(blueprint=auth.page, url_prefix='/auth')
from app.controllers import category
app.register_blueprint(blueprint=category.page, url_prefix='')
from app.controllers import course
app.register_bluepr... |
# Unicode CSV
def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
dialect=dialect, **kwargs)
for row in csv_reader:
# decode UTF-8 back to... |
from django.template import RequestContext
from django.shortcuts import render_to_response, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from rango.models import Category, Page, UserProfile
from... |
from datetime import datetime
from django.http import HttpResponse
from django.shortcuts import render
import requests
from bs4 import BeautifulSoup
from django.template.defaultfilters import safe
from pytz import timezone
import pandas as pd
# Create your views here.
# Grabs the text
def get_text(company):
page ... |
def main():
name = 'Lijun'
print('The name is', name)
name = name + ' Red'
print('New name is', name)
main()
def main():
count = 0
my_string = input('Enter a sentence: ')
for ch in my_string:
if ch=='T' or ch=='t':
count +=1
print(f'Letter T appears {count} times.')
... |
import socket
s = socket.socket()
s.connect(("localhost",3500))
str = input("Say Something : ")
while str!="exit":
s.send(str.encode())
data=s.recv(1024)
data=data.decode()
print("Server : ",data)
s1=input("Enter response : ")
s.send(s1.encode())
s.close()
|
# Generated by Django 3.2.4 on 2021-07-06 14:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pay', '0007_forms_made_by'),
]
operations = [
migrations.AlterField(
model_name='forms',
name='made_on',
... |
# Generated by Django 3.0.2 on 2020-04-02 09:14
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('obsapp', '0021_auto_20200401_1723'),
]
operations = [
migrations.AddField(
model_name='product',
nam... |
import random
import time
palavras = ('casa', 'abelha', 'cachueira', 'porta', 'mesa', 'lixeira', 'cadeado', 'guarda')
sorteio_palavras = random.choice(palavras) # Pegando palavras aleatorias
letras = []
tentantiva = 5
acertou = False
print('='*20 + ' JOGO DA FORCA ' + '='*20 + '\n')
print('Sorteando um palavra...'... |
import json
import pytest
from share.transform.chain import ctx
from share.transformers.v1_push import V1Transformer
class TestV1Transformer:
@pytest.mark.parametrize('input, expected', [
({
"contributors": [{
"name": "Roger Movies Ebert",
"sameAs": ["https://... |
import multiprocessing
import platform
import subprocess
import sys
import os
from conans.model.version import Version
from conans.util.log import logger
from conans.client.tools import which
_global_output = None
def args_to_string(args):
if not args:
return ""
if sys.platform == 'win32':
r... |
import os
import numpy
from pydub import AudioSegment
if __name__ == '__main__':
audioPath = 'D:/PythonProjects_Data/CMU_MOSEI/WAV_16000/'
labelPath = 'D:/PythonProjects_Data/CMU_MOSEI/Step1_StartEndCut/'
savePath = 'D:/PythonProjects_Data/CMU_MOSEI/Step2_AudioCut/'
if not os.path.exists(savePath): os.... |
"""
Crie um programa que leia vários números inteiros pelo teclado. O programa só
vai parar quando o usuário digitar o valor 999, que é a condição de parada.
No final, mostre quantos números foram digitados e qual foi a soma entre eles.
"""
n = c = s = 0
while True:
n = int(input('Digite um número: '))
if n ==... |
# This is the api for object oriented interface
import numpy as np
from math import pi
from scipy import interpolate
# The function assumes uniform field
def curl_2D(ufield, vfield, clat, dlambda, dphi, planet_radius=6.378e+6):
"""
Assuming regular latitude and longitude [in degree] grid, compute the curl
... |
# Esta é uma tentativa de analisar o método de Newton via programação em python
# Definir uma função
import math
def newton(f, flin, x0, epsilon, maxIter=50):
if math.fabs(f(x0))<= epsilon:
return x0
print("k \t x0 \t\t f(x0)")
k=1
while k<=maxIter:
x1=x0-f(x0)/flin(x0)
print("... |
# Simple extended BCubed implementation in Python for clustering evaluation
# Copyright 2020 Hugo Hromic, Chris Bowdon
#
# 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.apach... |
import andrimne.config as config
import andrimne.logger as logger
from andrimne.timer import Timer
import logging
import sys
def main():
timer = Timer()
config.read_main_configuration()
logger.configure()
steps = map(step_import, read_modules())
successful = True
for step in steps:
... |
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums) == 0:
return []
arr = []
for idx in range(0, len(nums)-1):
for val in range(idx+1,len(nums)-1):
if nums[idx]+nums[val] == target:
ar... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: yan
def hoemwork1():
dictionary = {
'good':'of a favorable character or tendenc',
'none': 'not any such thing or person',
'nice': 'very beautiful'
}
#长度
print len(dictionary)
#keys
print dictionary.keys()... |
from extensions import registry
from maltego_trx.entities import Phrase
from maltego_trx.maltego import MaltegoMsg, MaltegoTransform
from maltego_trx.overlays import OverlayPosition, OverlayType
from maltego_trx.transform import DiscoverableTransform
@registry.register_transform(display_name="Overlay Example", input... |
from selenium import webdriver
import os
import shutil
import time
import pandas as pd
def getWoocommerceOrder(fromdate, todate):
options = webdriver.ChromeOptions()
prefs = {}
prefs['download.default_directory'] = 'C:\\Users\\OEM\\Downloads\\woocommerceOrder'
options.add_experimental_option('prefs',... |
import os
for root,dir,files in os.walk("E:\Dom\programs\Extractors\Prey\star-citizen-texture-converter-v1-3\Extracted",topdown=False):
print(dir)
|
import numpy as np
import sys
vocab = {}
D = 5
with open("81.jl.out") as f:
for line in f.readlines()[:1]:
words = line[:-1].strip().split(" ")
words = list(filter(lambda x: x != "", words))
for idx in range(len(words)):
randd = np.random.randint(1, D + 1)
d = min(r... |
from .xboxcontroller import XboxController
from .buzzer import IllegalBuzzer
from .differentialdrive import DifferentialDrive
from .pca_motor import PCA9685
from .speedcontroller import SpeedController
from .speedcontrollergroup import SpeedControllerGroup
from .timer import Timer |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# diagnostic_node
# Info: Rosnode zum Testen des CAN-Datentransfers
# Input: Sämtliche Signale, die auf dem ROS-Bus liegen
# Output: - (nur externer Output der Dummy-Botschaft)
# Autor: Christof Kary (christof.kary@evomotiv.de)
# Version: 1.0, 04.06.2018
import... |
def init_api(api):
base_url = '/supply'
from . import resources
api.add_resource(resources.SupplyResource, f'{base_url}')
api.add_resource(resources.SpecificSupplyResource, f'{base_url}/<int:item_id>')
|
#!/usr/bin/env python
'''Execution script for DDR3 controller simulation.
PSU ECE 585 Winter'16 final project.
'''
__author__ = "Daniel Collins"
__credits__ = ["Daniel Collins", "Alex Varvel", "Jonathan Waldrip"]
__version__ = "0.3.5"
__email__ = "daniel.e.collins1@gmail.com"
import platform
import os
import sys
i... |
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
INT_MAX = 2 ** 31 - 1
INT_MIN = -2 ** 31
def div(a, b):
a = -a if a < 0 else a
b = -b if b < 0 else b
if a < b:
return 0
count = 1
tb = b
... |
from django.contrib import admin
from django import forms
from userena.utils import get_user_model
from userena.admin import UserenaAdmin
from userena import settings as userena_settings
from accounts.models import (Account,
AccountReminding,
InTheLoopSchedule... |
def GetPDFName(lhapdf_id, add_extension=True):
if lhapdf_id == 11000:
pdfname = "CT10nlo"
elif lhapdf_id == 10550:
pdfname = "cteq66"
elif lhapdf_id == 10042:
pdfname = "cteq6l1"
else:
print("LHAPDF ID {} not known.".format(lhapdf_id))
exit(1)
if add_extensio... |
""" RPG-lite Discord Bot """
import os
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='/')
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Game('Test Active'))
@bot.command()
@commands.bot_has_permissions(manage_messages=True)
async def clear(ctx... |
import uuid
from sqlalchemy.dialects.postgresql import UUID
from .base import db
from .mixins.base import BaseMixin
class Card(BaseMixin, db.Model):
__tablename__ = 'card'
title = db.Column(db.Text, nullable=False)
description = db.Column(db.Text, nullable=False)
comments = db.relationship('Comment', backr... |
import pyodbc
from validator import Validator as validator
validator = validator()
class Customer:
def __init__(self):
self.__customerId=""
self.__customerName=""
self.__customerAddress=""
self.__customerPhoneNumber=""
def searchAllCustomers(self,cursor):
try:
... |
#!/usr/bin/env python
import numpy as np
import corr, time, struct, sys, logging, socket
import h5py
import matplotlib.pyplot as plt
import hittite
roach = '192.168.42.65'
print('Connecting to server %s... '%(roach)),
fpga = corr.katcp_wrapper.FpgaClient(roach)
time.sleep(0.2)
if fpga.is_connected():
print 'ok\... |
# Generated by Django 2.2.4 on 2019-08-17 20:21
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('base', '0025_auto_20190817_2017'),
]
operations = [
migrations.AlterField(... |
price = float(input('Actual price: '))
promotionPrice = price-price*0.05;
print('Promotion price: ',promotionPrice) |
import pytest
from multiplication_tables import multiplication_tables
def test_two_by_two():
assert multiplication_tables(2, 2) == [[1, 2], [2, 4]]
def test_three_by_four():
assert multiplication_tables(3, 4) == [[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12]] |
"""
Purpose of this script is to train the model with kfold cross validation.
The evaluation metric is MSE and Pearson correlation.
Input: CSV file, train_list
Output: sav file (saved model), CSV file (PCC and MSE)
"""
import time
#time.sleep(15/60*60*60)
import pandas as pd
import pickle
import os
imp... |
# Cálculo de passagem com valores diferenciados
limiteKm = 200
km = float(input('Digite q quilometragem de sua viagem: '))
# Taxa Viagens curtas
taxMin = .5 * km
# Taxa viagens longas
taxMax = .45 * km
print('O valor de sua passagem será R$ {:.2f}'.format(taxMin if km <= 200 else taxMax))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 22 11:35:04 2021
@author: chulke
"""
import numpy as np
import matplotlib.pyplot as plt
def randomwalk(largo):
pasos=np.random.randint (-1,2,largo)
return pasos.cumsum()
def graficar():
N = 100000
i=0
fig = plt.figure()
l... |
from api import app
from api.user_list_api import user_list_api
app.register_blueprint(user_list_api)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
|
import pathlib
import numpy as np
import pandas as pd
import mlflow
from tqdm.notebook import tqdm
from sklearn.model_selection import KFold
def regression_cv(features,
labels,
model_factory,
metric,
folds,
mlflow_tags,
... |
# Generated by Django 2.0.7 on 2019-01-14 17:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('basedata', '0058_auto_20190114_1708'),
]
operations = [
migrations.AlterField(
model_name='device',
name='total_pric... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.