index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
985,600 | 923669c6123f515915ca7f88e91baed849f4cb35 | for x in "sathya":
print(x)
#-----------------
l = [1,2,3,4,5,6,7,8,9,10]
for x in l:
print(x)
#-----------------
#Working with Slice Operator
l = [1,2,3,4,5,6,7,8,9,10]
for x in l[3:8]:
print(x)
print("Thanks")
#-------------------
l = [1,2,3,4,5,6,7,8,9,10]
for x in l[:8]:
print(x)
print("Thanks"... |
985,601 | a2cf956800add12f7dde64c8a1fbced9935f98a6 | import sqlite3
import logging
import os
def initialize():
if(os.path.exists('chuj.db')):
return
conn = sqlite3.connect('chuj.db')
c = conn.cursor()
# tworzenie juserow
try:
c.execute('''CREATE TABLE IF NOT EXISTS USERS(
ID INTEGER NOT NULL PRIMARY KEY... |
985,602 | 1204bd7b2292617e37cb72fad00ff572d3ae32e5 | # coding:utf-8
import unittest
from airtest.core.api import *
import yaml, logging.config
yaml.warnings({'YAMLLoadWarning': False})
log_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../config/log.conf')
logging.config.fileConfig(log_file_path)
logger = logging.getLogger()
with open('../config... |
985,603 | 627f11dce62bd2d01cfa287f08240b8249d6a0a0 | import requests
from bs4 import BeautifulSoup
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import random
import time
import schedule
def spider_foods():
res_foods = requests.get('http://www.xiachufang.com/explore/')
bs_foods = BeautifulSoup(res_foods.text, 'html.parser')... |
985,604 | 743a2b86c2b880a1be6da5a9fad7e421485e80af | from django.shortcuts import render
from django.http import HttpResponse
from .models import Klassen, Richtingen, Leraren, Contact
def home(request):
return render(request, 'crud/index.html')
def aanbod(request):
alleRichtingen = Richtingen.objects.all()
return render(request, 'crud/aanbod.html', {'alleRi... |
985,605 | a32eb141dcc8b1e3f827166350c2cccb4cb16943 | # This module contains adapters and a facade for the different python netcdf libraries.
# $Id: opendap.py 4658 2011-06-13 15:41:23Z boer_g $
# $Date: 2011-06-13 17:41:23 +0200 (ma, 13 jun 2011) $
# $Author: boer_g $
# $Revision: 4658 $
# $HeadURL: https://repos.deltares.nl/repos/OpenEarthTools/trunk/python/io/opendap... |
985,606 | 371f65a57b9f22b9bbac0c7bb342a8af331373f7 | #!/usr/bin/python
import sys
import operator
import csv
# dictionary that contains the student id as the key and
# her/his reputation as the value
student = {}
# dictionary that contains the tag as the key and
# its score as value
tags = {}
# set the reader for the TSV data file
reader = csv.reader(sys.stdin, del... |
985,607 | e3ffa641b7f30f4e32dd2a54f1d3a23ff88cd471 | # Author: Daniel Martini Jimenez
# Date: 24-2-2019
from gurobipy import *
import math
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from write_to_text import *
# from path_planning import *
# ============================================================================
#
# Op... |
985,608 | 2d9352d7af85bc095fed7c845839db0f054be816 | """
Generic time series generator for two columns of data
"""
import matplotlib.dates as md
import matplotlib.pyplot as plt
import matplotlib.mlab as ml
import numpy as np
#import datetime as dt
import dateutil.parser as dp
#import cPickle
#import scikits.timeseries as ts
PATH = 'data.csv'
#Common Opt... |
985,609 | 9971f85c3f86c228a662af71378976f98ee1a425 | import pygraphviz as pgv
def plot_tree(nodes, edges, labels, name: str = "tree"):
g = pgv.AGraph()
g.add_nodes_from(nodes)
g.add_edges_from(edges)
g.layout(prog="dot")
for i in nodes:
n = g.get_node(i)
n.attr["label"] = labels[i]
name = name + '.png'
g.draw('images/' + name)
def write_fil... |
985,610 | 919cac514a460faa587ab0f6debde0a15a60f0b8 | import pytest
import bson
from datetime import date
from data_service.model.case import Case
from data_service.model.case_reference import CaseReference
from data_service.model.document_update import DocumentUpdate
from data_service.model.geojson import Feature, Point
from data_service.util.errors import ValidationErro... |
985,611 | b36c1a7a86cf763f8b7782ae99f708ca8d35d44d | # Python Crash Course: A Hands-On, Project-Based Introduction To Programming
#
# Name: Mark Lester Apuya
# Date: 05/23/2021
#
# Chapter 4: Working With Lists
#
# Exercise 4.4 One Million:
# Make a list of the numbers from one to one million, and then use a for loop
# to print the numbers. (If the output is taking too... |
985,612 | 75ccadc134017d5eb045f5d39da5bf4fa28555f1 | import requests
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.uix.listview import ListItemButton
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition
from kivy.properties import StringProperty
import patient
class Edit(BoxL... |
985,613 | 809c93ae3debb5eaed8ef51872898eeafafb4d32 | from model import db, DietPreference, ExcludedIngredient
def set_food_preferences(session):
"""Setting saved diet and ingredient exclusions for registered users"""
if 'user_id' in session:
diet, health = get_diet_preferences(session['user_id'])
exclusion_list = get_ingred_exclusions(session['u... |
985,614 | 21a2e1625964284814a6bc9f5ceb6f497de3866a | from sklearn_django.settings import BASE_DIR
class Params:
BAD_STATUSES = ('true', 1, '1')
ALGORITHMS = ['adaboost', 'gausnb', 'decisiontree', 'gradientboost', 'logregression', 'linear_sgd','xgboost'
,'lightgbm', 'kneighbors']
COMPARE_RESULT_URL = '/media/exp/compare-results.csv'
COMPARE_RESULT... |
985,615 | 6e0b0615a940491d8597c3039d4cfb510c4aa416 | from .ecr import ECRImages # noqa: F401 (unused)
from .images_base import Images # noqa: F401 (unused)
from .local import LocalImages # noqa: F401 (unused)
|
985,616 | e8ee7651d8f7cb0fce60b206be693fafd85426f6 | import os
import os.path
import json
import collections
import configparser
import glob
import re
from delphi.dof import DOFFile
from ello.sdk.git import get_sorted_tags
class ProjectMetadata:
def __init__(self, _filename=None):
self._metadata = {}
self._filename = _filename or 'package.json'
... |
985,617 | b78967f9969c2bf1d7989d2d1c1ad10e597dac28 | import random
import numpy as np
import math as m
import k_helper as kh
x1 = np.array([3, 4, 4, 5, 5, 5, 5, 6, 6, 6, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10])
x2 = np.array([5, 5, 6, 4, 5, 6, 7, 5, 6, 7, 2, 2, 3, 4, 2, 3, 4, 2, 3, 4])
data = np.column_stack((x1, x2))
k = 3
def initialize_k_medoids(k, Data):
medoids = n... |
985,618 | 0f01bddccdb787ae7a2eb96b40e3fd2609f34593 | #!/usr/bin/python3
def uppercase(str):
for x in str:
flag = 0
if ord(x) >= 97 and ord(x) <= 122:
flag = 32
print('{:c}'.format(ord(x) - flag), end="")
print()
|
985,619 | 390657fdfc870eae8cdb5415369d390103214c51 | import time
from textwrap import dedent
time.sleep(5)
print(
dedent("""{
"text": "Золушка — советский чёрно-белый художественный фильм-сказка, снятый на киностудии Ленфильм режиссёрами Надеждой Кошеверовой и Михаилом Шапиро по сценарию Евгения Шварца. Золушка — советский чёрно-белый художественный фильм-ска... |
985,620 | 5ed1198a5d600f3c1e41d236287fabf2a1075106 | from bs4 import BeautifulSoup
import requests
import time
import re
from tokens import url
def get_info():
r = requests.get("https://www.warmane.com/information")
data = r.text
soup = BeautifulSoup(data, "lxml")
outland = soup.find_all("div", {"class": "stats"})[1].find_all("div")
players = str(o... |
985,621 | e640aba17aa44a770c528cda1f7a786644897e72 | from django.db import models
from django.urls import reverse
# Create your models here.
class User(models.Model):
# author = models.ForeignKey('auth.User')
user_id = models.CharField(max_length=50, unique=True)
password = models.CharField(max_length=200)
class asset(models.Model):
user_id = models.F... |
985,622 | d94ada86ad7f2e449268f3c60d8c70f52595d07e | # Copyright 2018 Oinam Romesh Meitei. All Rights Reserved.
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under th... |
985,623 | d4e5651e0d4911684e06d13bc41b0f039bb1e9d4 | import sys
import time
import datetime
import logging
import cPickle as pickle
import os
import numpy as np
import torch
# import cv2
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from helpers.datagenerator import DataGenerator, Fake... |
985,624 | bd499996b62d5f9ccc4ab6d0c1b873d776018050 | from django.db import models
# reverse allows us to reference an object bty its URL template name
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
body = models.TextField()
def __str__(s... |
985,625 | 39fb9e9e7ab5f9b4a0ecfc00fb89014b88cbc263 | import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import psycopg2
import json
import pandas as pd
import time
app = dash.Dash(__name__)
#app.css.config.serve_locally=False
#app.css.append_css(
# {'external_url': 'https://codepen.io/amyosh... |
985,626 | a2fe3dafaeddfdda38e2a1deac011b6d0af0db55 | # -*- coding: utf-8 -*-
#
# brunel-delta-nest.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the Licen... |
985,627 | ce4ad01c755094edd053b653fc2e3baf0106cf4d | import numpy as np
import scipy as sc
import os, re
import matplotlib.pyplot as plt
from prettyprint import pp
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.naive_bayes import BernoulliNB, GaussianNB, MultinomialNB
from sklearn.metrics import confusion_matrix, f1_score, accu... |
985,628 | 780afdffab76d7c1f4d5ab7994c9b754e18281d2 | from datetime import datetime, timedelta
from config import BaseApiConfig
from src.api.pool.services.location_services import LocationFormService
from src.api.pool.services.meeting_services.meeting_time_services.meeting_location_service import MeetingLocationService
from src.message_queue.tasks.email_tasks.base_email_... |
985,629 | c9f785d02481dfdec6b7f62d5bde3d2b986fd811 | # imports
print("""
|******************|
| Desafio085 |
|******************|
""")
print("7 Valores Numéricos")
print()
# Variáveis
nums = [[], []]
for c in range(0, 7):
num = int(input(f"Digite o {c+1}º número inteiro: "))
if num % 2 == 0:
# Par
nums[0].append(num)
else:
# I... |
985,630 | 3daa44b373b61c996966af491da768641f90fb3e | def nth_fibonacci(n):
arr = [1,1]
for i in range(2,n+1):
newfib = arr[i-1] + arr[i-2]
arr.append(newfib)
return arr[n-1]
|
985,631 | 53129993d24f8bd994955f924aa9ec0e4c9656cf | # bz2_file_write.py
import bz2
import io
import os
data = 'Il contenuto del file esempio va qui.\n'
with bz2.BZ2File('esempio.bz2', 'wb') as output:
with io.TextIOWrapper(output, encoding='utf-8') as enc:
enc.write(data)
os.system('file esempio.bz2')
|
985,632 | ef98786c7a10a9a405df253fd300e9f73a41d64c | from django.views.generic.base import View
from product_management.forms import CategoryForm, ProductForm
from product_management.models import Category, Product
from django.shortcuts import render, redirect, get_object_or_404
class HomeView(View):
def get(self,request):
return render(request,"index.html")
... |
985,633 | f549171088f0e49afecd075a20c328834a71fc0b | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-04 04:52
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('support', '0014_auto_20170803_1831'),
]
operations = [
migrations.RenameField(
... |
985,634 | a3614bb6ef91b00c89aff65d5906caf3241a3c06 | from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
@app.get("/user/{user_id}")
async def userDataFetch(user_id):
return {"user": user_id, "msg": "FETCHED SUCCESS FULLY", "code": 200}
@app.get("/admin/{user_id}")
async def AdminDataFetch(user_id):
return {"admin": user_id, "msg": "FETCH... |
985,635 | d67da19b48bc81dfa931c06a620a1e0e997c4aa2 | # 8.2从同一个目录导入蓝图对象
from info import db
from . import api
from flask import session, render_template, current_app, jsonify, request, g
from info.models import User, News, Category
from info.utls.response_code import RET
from info.utls.commons import login_required
# 8.3使用蓝图对象,项目首页展示
@api.route('/')
@login_required
def in... |
985,636 | 9ac910bf73575e1e4a8d51c263c7947c71be4b2e | from datetime import date, datetime, timedelta
from coinapi_service import coin_api_get_exchange_rates
import json
from os import path
'''
date1 = date.today() # date du jour
#date2 = date1 + timedelta(10) # additionner / soustraire des jours
date3 = date(2021, 1, 30)
diff = date1-date3
# print(diff.days)
date3_str =... |
985,637 | 2268ccd366003d64a1af5d62e19344aea3a05b34 | from django.conf.urls import url
from .views import *
urlpatterns = [
url(r'^customers/$', customer_list),
url(r'^customers/', customer_detail),
url(r'^customers/age/', customer_list_age),
] |
985,638 | 0f6afec1a29283dfe311b8ce55c6dbd6d80be438 | #!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
import pika
import sys
import config
CHUNK_SIZE=6
class MqMessage():
def __init__(self):
user = config.rabbitmq['user']
passwd = config.rabbitmq['passwd']
host = config.rabbitmq['host']
cred = pika.PlainCredentials(user, passwd)
params = p... |
985,639 | c38d57ad646cfb08b2c44adb22bc97e05a2f4636 | import os
import csv
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
def main():
"""Init tables and seed books.csv"""
db.execute("DROP TABLE IF EXISTS books_tmp;")
... |
985,640 | 6b91fd5752813205a9527ad8230b797ca2168328 | from odoo import api, fields, models, tools, _
from datetime import datetime, timedelta
from odoo.exceptions import UserError
import pytz
from odoo import SUPERUSER_ID
class PosMakePayment(models.TransientModel):
_inherit = 'pos.make.payment'
@api.multi
def type_cash(self):
cash = self.session_id... |
985,641 | 6c2fb4d570326b7b7b2f75ef508d48096db4c9f6 | def delete(x,y,board):
"""
Function used to delete nums from board and replace them with 0
"""
board[x][y] = 0
def turn(board):
temp = [
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]
]
for i in range(len(board)):
for j in range(len(board)):
... |
985,642 | 9c638051584415bd480bda0d388ba13e2a775d01 | import numpy as np
from knodle.evaluation.majority import majority_sklearn_report
def test_majority_vote_no_match():
z = np.zeros((2, 4))
t = np.zeros((4, 2))
z[0, 0] = 1
z[1, 1] = 1
t[0, 0] = 1
t[1, 0] = 1
t[2, 0] = 1
t[3, 0] = 1
y = np.array([1, 1])
report = majority_skle... |
985,643 | 2d33e2d0673aec1c6f385371e5e57779831a3603 | import numpy as np
from skimage.measure import profile_line
from skimage.measure.profile import _line_profile_coordinates as lpcoords
from skimage import io
from skimage import draw
import trace as tr
from matplotlib import pyplot as plt, cm
im = io.imread('zebrafish-spinal-cord.png')
img = np.dstack([np.zeros_like(im... |
985,644 | 4a5fb33aca30d67ac5a9ec01f3318035bb5ca5ea | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
import math
from models_binary import OPS, constrain
PRIMITIVES_TRIPLE = ['0_plus_multiply', '0_plus_max', '0_plus_min', '0_plus_concat',
'0_multiply_plus', '0_multiply_max', '0_multiply_min... |
985,645 | 255a279a11aa5f61f84e959858e7001cae3114d4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# Copyright (c) 2019 Baidu.com, Inc. All Rights Reserved
#
################################################################################
"""
File: source/encoders/attention.py
"""
import ... |
985,646 | 35fef18599254891ac8cbe3cc62e8e15e90d3926 | def is_prime(num):
i=1
factors=0
while i<num:
if num%i==0:
factors=factors+1
i=i+1
if factors==1:
return True
if factors>=1:
return False |
985,647 | 5e0b54757f05feb78d4142f5e51b929c441d20bc | from selenium import webdriver
import time
class DouyuSpider(object):
def __init__(self):
self.option = webdriver.ChromeOptions()
self.option.binary_location = r'D:\谷歌浏览器\Google\Chrome\Application\chrome.exe'
self.driver = webdriver.Chrome(chrome_options=self.option)
self.... |
985,648 | aec0726b90feffea01e6f7a1292415bde88c4b3f | """
Morgan Christensen
Simple calculator project to get used to tkinter
"""
from tkinter import *
# number storage
numbers = []
# functions
def add():
numbers.append(e.get())
global math
math = "addition"
# print(numbers)
e.delete(0, END)
def subtract():
numbers.append(e.get())
global ... |
985,649 | 98cbdcca3c3706a8ebf59d02b1e2afe1f170201b | # Generated by Django 3.0.8 on 2020-07-24 15:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('todolist', '0002_todo_duesness'),
]
operations = [
migrations.RenameField(
model_name='todo',
old_name='duesness',
... |
985,650 | 416e075527b4b00af2606006a521ea0017f3f919 | import asyncio
import pytest
from PLATER.services.util.overlay import Overlay
@pytest.fixture()
def graph_interface_apoc_supported():
class MockGI:
def supports_apoc(self):
return True
async def run_apoc_cover(self, idlist):
return [{
'result': [
... |
985,651 | 669ae5e6eea2ba099ac0903a3534bb75e71e339a | import time
s=0
m=0
while s<=60:
print m, 'Minutes', s, 'Seconds'
time.sleep(1) #program stops for 1 second
s+=1
if s == 60:
m+=1
s=0
elif m == 60:
m=0
s=0 |
985,652 | 9df01959d226cc1eb6ccdf0e16006be37274ec9c | """
Jesse@FDU-VTS-MIA
created by 2019/11/26
"""
class Solution:
def longestPalindrome(self, s: str) -> str:
ans = self.expand_center(s)
return ans
def dp(self, s):
"""
TLE
"""
n = len(s)
if not n: return ""
P = [[False for j in range(n)] for i i... |
985,653 | 58a879dd27bc12ccf2d073c43092e691568f9c21 | N = int(input('Quantos alunos? '))
students = {}
for i in range(1, N+1):
name = input(f'Nome do aluno {i}: ')
notas = []
for j in range(1, 5):
nota = float(input(f'{j}ª Nota do aluno {name}: '))
notas.append(nota)
students[name] = notas
for name, notas in students.items():
average = sum(notas) / ... |
985,654 | eef3bd17f539f9e98be515c5175279aa4a223e38 | from flask import Flask
import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename
import cv2
from class_CNN import NeuralNetwork
from class_PlateDetection import PlateDetector
# Load pretrained model
########### INIT ###########
# Initialize the plate detector
plat... |
985,655 | 16385e255196882b33d297809f3086fa4516ccb2 | import asyncio
import aiohttp
import sys
import json
import random
def generate_cmd(cmd, id_, timestamp):
return {"cmd": cmd,
"id": id_,
"expire_time": timestamp}
async def test_client(loop, account_number, node_id):
basic_auth = aiohttp.BasicAuth(account_number, "imapassord")
sess... |
985,656 | 9a2773c39713bb3b7568c05e8b1bcecd66bcb960 | from ..consts import NOTHING # noqa
from .config import Config, ParameterError # noqa
from .parameter_types import String, Integer # noqa
from .spec import Spec # noqa
|
985,657 | d0d2f36f03c2b06f76e3e4f0e3835487a194cd11 | """
Basic Views for the Inventory System
"""
from django.shortcuts import render
#front page
def inventory_greeter(request):
template = 'inventory/inventory_greeter.html'
context = {}
return render(request, template, context)
|
985,658 | 394378bd14739d374c7b1e70699fe78aabb47164 | #!/usr/bin/env python3
"""
Module for processing the Human Phenotype Ontology.
"""
__author__ = 'Orion Buske (buske@cs.toronto.edu)'
import os
import sys
import re
import logging
logger = logging.getLogger(__name__)
class HPError(Exception):
pass
class HPObsoleteError(HPError):
pass
def get_descendants(r... |
985,659 | 215f0e526142298bff10da363b3b7c0eff11c282 | from __future__ import division
import pandas as pd
import numpy as np
from preprocess_data import update_with_cc_means
# from generate_features import cat_to_binary
from sklearn import preprocessing, cross_validation, svm, metrics, tree, decomposition, svm
from sklearn.ensemble import RandomForestClassifier, ExtraTree... |
985,660 | 7ada3469551de8b8ec5895dc7d01907afc571862 | from .range import *
from .expr import *
from .decl import *
__all__ = ['Location', 'Range'] + expr.__all__ + decl.__all__
|
985,661 | 8b22655edded8cc4d8afdade99c629471344494e | import unittest
import time
from src.store import Store
class TestStore(unittest.TestCase):
def test_cache_get(self):
store = Store(retry=0, expiry=20)
store.cache_set('bonnie', 'clyde')
value = store.cache_get('bonnie')
self.assertEqual(value, b'clyde')
def test_timeout_def... |
985,662 | c3d5e2640fd1017a9cf520f26e666cc8cd71ad6d | """
BFS 是常见的广度优先搜索算法(Breadth-First-Search),是一种利用队列实现的搜索算法。
先探索其实点周的node,像四周扩散
"""
# init the graphs data
graphs = {
'A': ['B', 'C'],
'B': ['A', 'C', 'D'],
'C': ['A', 'B', 'D', 'E'],
'D': ['B', 'C', 'E', 'F'],
'E': ['C', 'D'],
'F': ['D']
}
def bfs(graph, s):
"""
implement the bfs
:... |
985,663 | 4f5117c3c14b348a1e4828a3f007f86394ae8434 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Load all import
import tweepy
import sys
from unidecode import unidecode
from ConfigParser import SafeConfigParser
# Set configuration
reload(sys)
sys.setdefaultencoding('utf8')
class Twitter:
def __init__(self, config):
# Load configuration from config.in... |
985,664 | d1d7f4587159832b8a31d94f67b0deaf88a44016 |
#! /usr/bin/python3
''' file to infer the critical values of delta likelihood to infer
aneuploidy '''
import pandas as pd
import re
import matplotlib.pyplot as plt
import statsmodels.api as sm
import statsmodels.formula.api as smf
import numpy as np
from sklearn.preprocessing import OneHotEncoder
#import the data
... |
985,665 | 2cb17f61e707c431d2083b0598fece61c0f7b7d2 | #coding=utf-8
from __future__ import print_function
from __future__ import division
import tensorflow as tf
import os
import cv2
import numpy as np
import datetime
from yolov3 import yolov3_body
from yolov3 import yolov3_loss as Loss
from datasets import Dataset
import config
flags = tf.app.flags
FLAGS = flags.FLAGS... |
985,666 | d8cc15ea3486f39c8b211f427ccf635363383822 | import base64
import contextlib
import hashlib
import sqlite3
import time
def sha1(val):
s = hashlib.sha1()
if isinstance(val, str):
val = val.encode()
s.update(val)
return s.hexdigest()
def create_connection(db_path):
conn = sqlite3.connect(db_path)
conn.create_function('sha1', 1, s... |
985,667 | ee86ba8a151cb308daf7ef5f2f3cabdef9a121d8 | from django.shortcuts import render, get_object_or_404, reverse, redirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db.models import Q
from .forms import VendorForm, DeliverTownForm, DeliverPostalForm
from .models import Vendor, VendorDeliver... |
985,668 | 37b5d5164c5eb1c9f9acb1bb58b85d3a2fe14c8b | ##### import packages
#base
import os
from collections import defaultdict
import numpy as np
import scipy.stats
from matplotlib import pyplot as plt
import random
import pyreadr
import numpy as np
import pandas as pd
import seaborn as sns
# %matplotlib inline
# %autosave 30
#pyro contingency
import pyr... |
985,669 | af9a19874c5d4ddbc410a4901b3a7b1f8c6c929d | # ################################################### #
import math
import random
import sys
import time
import PIL.Image
from modules import colorutils
from PIL import Image, ImageDraw
"""""" """""" """""" """""" """""" """""" """""" """""" """""" """""" ""
def drawRects():
global config
changeColor(config.colo... |
985,670 | b7e411ed82bfe115f38b406c5abaefbf6b17c5c0 | # feat/test2 - a
# feat/test
country = "United States of America"
# slicing
# substring. get string begin at index 5.
print(country[5:])
# get first 5 chars
print(country[:5])
# defined starting point:ending point/index up to but not including
print(country[5:10])
|
985,671 | 5c5c8d0788bd2f90b8ce79e93e3c2d351a0831e2 | from arduino.arduinoparallel import ArduinoParallel
class PortMock:
def __init__(self, port='COM5', baudrate=115200, parity='N', bytesize=8, stopbits=1, timeout=1):
self.port = port
self.baudrate = baudrate
self.parity = parity
self.bytesize = bytesize
self.stopbits = stop... |
985,672 | 81d014313ea6cb9dfc2971651f179ab881c69596 | # implemented by Fengyu
from flask import Flask, request, Response, make_response, session
import requests
import json
import argparse
import logging
import sys
import logging
from flask_cors import CORS
# email
from flask_mail import Mail
# database import
from tinydb import TinyDB, where, Query
db = TinyDB('users... |
985,673 | b69f8670a05f381cbc441ef88615c0fd10ad007b | from sqlalchemy import Column, ForeignKey, Integer, String, Boolean
from sqlalchemy.orm import relationship
from database.db_entity_collection import BaseModel
class MonstersWeapons(BaseModel):
__tablename__ = 'monsters_weapons'
id_monsters_weapons = Column(Integer, primary_key=True, unique =True)
id_mons... |
985,674 | 096489f172bb80442f6cddaec4a5d82c4fd6aa81 | from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtGui import *
from email import Encoders
from email.MIMEBase import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import os
import smtplib... |
985,675 | e33a894aa5e8c3b69fecbd2885ae92abc9e879c0 |
class Config(object):
'''
保存网络的配置信息
'''
data_path = 'data/'
num_workers = 4
image_size = 96 #图片尺寸
batch_size = 128
max_epoch = 200
lrG = 2e-4 #生成器的学习率
lrD = 2e-4 #鉴别器的学习率
gpu = True
nz = 100 #噪声维度
ngf = 64 #生成器feature map数
ndf = 64 #判别器feature map数
save_path... |
985,676 | c3b875b92e082d8c29cd17641023c983934d553a | #!/usr/bin/python
# -*- coding: utf-8
from setuptools import setup, find_packages
pkg_vars = {}
setup(
name='ddns',
author='Selçuk Karakayalı',
author_email='skarakayali@gmail.com',
url='https://github.com/karakays/ddns',
description='Dynamically update DNS records of the enclosing environment',
... |
985,677 | a8c24623fbd346260abac82cf665d641977d8067 | from django.contrib.auth.models import User
from django.db import models
class Job(models.Model):
title = models.CharField(max_length=255)
short_description = models.TextField()
long_description = models.TextField(blank=True, null=True)
created_by = models.ForeignKey(User, related_name='jobs', on_dele... |
985,678 | 935f90addbb5aaebcf769011b6f51b104b6e02da | from peewee import *
db = SqliteDatabase('sqlite3.db')
class Question(Model):
question_text = CharField()
#pub_date = DateTimeField("date published")
class Meta:
database = db
def __str__(self):
return self.question_text
class Choice(Model):
question = ForeignKeyField(Question, backref='choices')
choi... |
985,679 | 3703565199a347c0c75dc917829649c090d9ad0d | from django.shortcuts import render,HttpResponse,redirect
from .models import Blog,Comment
from django.contrib import messages
from django.views import View
# Create your views here.
class home(View):
def get(self,request):
posts=Blog.objects.all()
content={'allposts':posts}
return render... |
985,680 | b0d57a2ba0422497cead0b2ed2a527b2d9811b3a | from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import Http404
from serializers import RentSerializer
from permissions import IsOwnerReadOnly
from rest_framework import viewsets
from models import Equipment
from rest_framework.response import Response
from rest_fra... |
985,681 | 1cefe6e48c85783a43ebd4a8170831e6e24c3ed9 | # https://www.youtube.com/watch?v=BuIsI-YHzj8
# http://deeplearning.net/tutorial/gettingstarted.html
import numpy as np
import matplotlib.pyplot as plt
import theano
import theano.tensor as T
# GPU acceleration
# theano.config.device = "gpu"
"""
>>> np.linspace(-1, 1, 11)
array([-1. , -0.8, -0.6, -0.4, -0.2, 0. ,... |
985,682 | 9cb110c267e4f1c9c221cd48a2e6eba998e76053 | # SConscript for lib subdirectory
# Import envrionment
Import('env')
# Now get list of .cpp files
src_files = Glob('*.cpp')
objs = env.Object(src_files)
yaml_objs = SConscript('yaml/SConscript')
bson_objs = SConscript('bson/SConscript')
if env['tests'] == True:
gtest_libs = SConscript('gtest/SConscript')
else:... |
985,683 | 1b0a1ebd9fc8c558e0d79588b97e0e1ac72220e2 | def getchr(plus,txt,it=97):
if(txt.isupper()):it=65
tmp = ord(txt) - it # 0-25 input
tmp = (tmp+plus)%26 # 0-25 ans
return chr(tmp + it)
plus = int(input())
txt = input()
print(getchr(plus,txt)) |
985,684 | 9f6db5d95956f526bb743b5c9b64aefc918fcca3 | from django import forms
from django.forms import ModelForm,Select
from .models import Messages,UserInfo,DoctorMessageMapping
import drchronoAPI
TIME_CHOICES=[]
for h in xrange(24):
for m in ['00','30']:
t='{:02d}:{}:00'.format(h,m)
TIME_CHOICES.append((t,t[:-3]))
class UserInfoForm(Mo... |
985,685 | a3928a534a678cd8c8304ed6de5bf0abc04e4c5e | import math
import numpy.linalg as LN
import numpy as np
ep = lambda p,b: p*b
is_close = lambda old, new, e: LN.norm(old-new) <= e
def meanshift_segmentation(im, features, bandwidth):
cluster_means = []
points = range(features.shape[0])
np.random.shuffle(points)
points = set(points)
while len(... |
985,686 | a7a526182e964cb87951911494c13aed1703fc70 | #!/usr/bin/env python3
#__*__coding: utf8__*__
import requests
url = 'http://www.goubanjia.com'
header = {
'User-Agent':'Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0',
'Referer': 'http://www.baidu.com',
}
r = requests.get(url, headers=header)
#print(r.text)
print(r.json()) |
985,687 | f909fde49b9dd5a51693232a4eefef30c79f6aaf | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pupil', '0004_auto_20160214_1454'),
]
operations = [
migrations.DeleteModel(name="User_info"),
migrations.DeleteModel(... |
985,688 | 214d4fac7534d4c2b3ca09f8c7123c2ffd7d53e9 | #Tp Relations
class Ville:
"""Ville"""
def __init__(self,nomVille):
self._nomVille = nomVille
self._batiments = []
@property
def nomVille(self):
return self._nomVille
@nomVille.setter
def nomVille(self,v):
self._nomVille = v
#Methodes de gestion de la liste des bâtiments
def get_batiments(self):
ret... |
985,689 | 0a3b0d5a842aa0bef2388bf309adb6369513fff7 | import pandas as pd
import plotly.express as px
df = pd.read_csv("Size of TV,_Average time spent watching TV in a week (hours).csv")
fig = px.scatter(df, x="Size of TV", y="\tAverage time spent watching TV in a week (hours)")
fig.show() |
985,690 | 1f2dce411ccdff82d8d431a1881c314f8dbfad1a | ################################################################
## Simple Calculator App (Jython) ##
## Author: Nick Belli ##
## Date: 04/18/2018 ##
## Uncomment popup boxes for testing and training purposes... |
985,691 | 4182f473f8f52f2cdd61a4757d6c08da5a998d92 | from client import CLIENT
import argparse
from threading import Thread
import datetime
from concurrent.futures import ThreadPoolExecutor
def argv():
# Create parser
arg_parser = argparse.ArgumentParser()
# Add arguments
arg_parser.add_argument('-t', '--test', help='Specify which test to run')
arg_p... |
985,692 | d2eff1a2eb951446d26aee40a608fc38c123da20 | from bar import foo
def f():
foo.boring_function()
foo.interesting_function()
|
985,693 | 9dd14ca34a57355095322387974dad65c127b738 | from math import pi, sqrt
class Triangulo:
def __init__(self, opcion: str):
self.opcion = opcion.lower() #Convierte a mminusculas.
def Program(self):
try:
if self.opcion == "perimetro":
perimetro = self.__HallarPerimetro(float(input("Lado 1: ")), float(input("La... |
985,694 | 69f9ae86070822b356cad95b0eaa1aef8d1e8593 | #!/usr/bin/env python
from setuptools import setup, find_packages
try:
from pyqt_distutils.build_ui import build_ui
cmdclass = {'build_ui': build_ui}
except ImportError:
cmdclass = {}
setup(
name='foo',
version='0.1',
packages=find_packages(),
license='MIT',
author='Colin Duquesnoy',
... |
985,695 | efe6f428be1505287aa4a1139c6cf39be325aa26 | # https://www.geeksforgeeks.org/finding-all-subsets-of-a-given-set-in-java/
def subsets_of_set_bits(input_set):
list_set = list(input_set)
num_elements = 2**len(list_set)
num_bits = len("{0:b}".format(num_elements-1))
all_subsets = []
for i in range(0, num_elements):
binary = "{0:... |
985,696 | 7219de952e40f642169621728b86111abfa7c7a4 |
from soz_analizi.shekilci import *
from soz_analizi.shekilciler import *
from operator import itemgetter
#from soz_analizi.luget.rama_doldur import efsane
dey_isim=['is.']
dey_feil=['f.']
dey_evez=['ev.']
dey_sif=['sif.']
dey_say=['say.']
dey_zerf = ['z.','zer.']
hallanan=['Isim']
mensub=['Isim']
import os
cala={'isi... |
985,697 | f1dafc72224edd41f3360c73e23e53a89958e3dc | import socket, sys, threading
import json
import signal
import time
import os
def exit_gracefully(signum, frame):
# restore the original signal handler as otherwise evil things will happen
# in raw_input when CTRL+C is pressed, and our signal handler is not re-entrant
signal.signal(signal.SIGINT, ... |
985,698 | d12b98cd70346b50fb5d10a8026e54a60d638c9d | import pandas as pd
import numpy as np
from sklearn import preprocessing
from sklearn.ensemble import RandomForestRegressor
import pickle
from sklearn.decomposition import PCA
from mlc.utility.FeatureUtil import FeatureVector
from sklearn.preprocessing import LabelEncoder
from csv import DictReader
"""
original
"""
cla... |
985,699 | a2888df4b521f2ff3497154a3b6cc2e2f70c586e | def anagram(s, t):
freq = dict()
for letter in s:
if letter in freq:
freq[letter] += 1
else:
freq[letter] = 1
for letter in t:
if letter in freq:
freq[letter] -= 1
if freq[letter] < 0:
return False
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.