index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
12,500 | e33b92e58866e85ec83c316c6ec053995de1d522 | import pandas as pd
from sklearn.datasets import load_wine
wine = pd.read_csv(filepath_or_buffer='wine.data',header=0)
df.columns=['class', 'Alcohol', 'Malic_Acid', 'Ash', 'Alcalinity of Ash', 'Magnesium',
'Total Phenols', 'Flavanoids', 'Nonflavanoid Phenols', 'Proanthocyanins', 'Colour Intensity', 'Hue',... |
12,501 | 509eec4a09556408d9785ad9eeffb07ca545d54a | from django.shortcuts import render
from .models import Article
# Create your views here.
def news(request):
news_articles = Article.objects
return render(request, 'news.html', {'news_articles': news_articles}) |
12,502 | 454f068d4b88865db55d1a8ea9d9b72954d82026 | import pygame
from pygame.locals import *
import sys
import random
# Global variable for game
FPS = 32
SCREENWIDTH = 289
SCREENHEIGHT = 511
SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) # initialising display for game
GROUND_Y = SCREENHEIGHT * 0.8
GAME_SPRITES = {} # this is use to store i... |
12,503 | 3891fc2584ff0230f891cf0d4732ce23e2526472 | import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 1234))
s.listen(10) # кол-во очереди за соединением
while True:
conn, addr = s.accept()
while True:
data = conn.recv(1024)
if not data: break
else:
conn.send(data)
conn.close() |
12,504 | c175739b838959b6554b4d81886c7c826f6b3b9c | from django.core.management import setup_environ
import settings
setup_environ(settings)
import psycopg2
import os
from datetime import datetime
from utilities.notifiers.Email import Email
from utilities.notifiers.emailNotifier import emailNotifier
def flaggedSessions(curr):
q = """
select s.name
from pht... |
12,505 | 060977d2c50cb4906537464ef984c69907d39eb0 | import cv2 #pip install opencv-python
# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)# if you have more than one cam change to 1
# To use a video file as input
# cap = cv2.VideoCapture('filename.mp4')
print("Press q If you Want to Exit")
whil... |
12,506 | 9aae60506928c519789416e365eb914e926ac6b7 | import re
#read files and store lines into a list of strings
with open(r'C:\Users\xrist\OneDrive\Υπολογιστής\two_cities_ascii.txt')as f:
lines=f.readlines()
romain_numbers_list=['I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII','XIII','XIV','XV','XVI','XVII','XVIII','XIX'
,'XX','XXI','XXII'... |
12,507 | a28d8890d5221775d92cb2b0efd762e1d5c7199d | dicts={
"hola":15,
"chau":65,
"adios":4154,
}
print(list(dicts.keys())) |
12,508 | 768d040a6b969abdc7920f144d28a7b8c26f041d | from django.db import migrations, transaction
def copy_slack_account(apps, schema_editor):
BigEmoji = apps.get_model('bigemoji', 'BigEmoji')
while BigEmoji.objects.filter(owner__isnull=True).exists():
with transaction.atomic():
for row in BigEmoji.objects.filter(owner__isnull=True):
... |
12,509 | c44411b89821cfa1ed2b1403d5cbbdbdd0bcdb01 | f = open("새 파일.txt",'w') #파이썬 소스코드가 있는 경로가 기본 경로임
f.close() |
12,510 | 4984bcc657c473e377a8a363db156d8c29df4aeb | from scrapy import Spider
from scrapy.http import FormRequest
from scrapy.utils.response import open_in_browser
class QuotesSpider(Spider):
name = 'quotes'
start_urls = ('http://quotes.toscrape.com/login',)
def parse(self, response):
token = response.xpath('//*[@name="csrf_token"]/@value').ext... |
12,511 | ef963089e8e2eebda1fad7b5befffbaf31889bd2 |
import ruamel.yaml
import canonical # NOQA
def test_canonical_scanner(canonical_filename, verbose=False):
with open(canonical_filename, 'rb') as fp0:
data = fp0.read()
tokens = list(ruamel.yaml.canonical_scan(data))
assert tokens, tokens
if verbose:
for token in tokens:
... |
12,512 | 9ecdef13d6afef4ff81ed05171e54bc71678f7ac | # Copyright Pincer 2021-Present
# Full MIT License can be found in `LICENSE` at the project root.
"""Sent when a channel is created/joined on the client."""
from __future__ import annotations
from typing import TYPE_CHECKING
from ..core.dispatch import GatewayDispatch
from ..objects.guild.channel import Channel
from... |
12,513 | 226a91cf43a3fca38edd5ed67de85bcd8309b067 | from .forms import Forms
from .form import Form
__all__ = ['Forms', 'Form'] |
12,514 | 5378c22b3a2c5566f060f911734a3b8c42b191fe | import sys
import math
import numpy as np
class Seidel:
def __init__(self, exercise, error):
self.exercise = exercise
self.error = error
self.start()
def start(self):
if self.verifyLines(self.exercise):
self.seidel(self.exercise)
else:
if se... |
12,515 | dd263598528cc835b08287e558a631b3dc822110 | import sys
import pwm
def shell():
sys.stdout.write(b"ESP32 UART brightness control loop...\n")
sys.stdout.write(b"Type 'repl' to return to micropython REPL.\n")
led_ctrl = pwm.iMacBrightnessPWM(2, 1000, 0)
imac_ctrl = pwm.iMacBrightnessPWM()
brightness = 0.2
led_ctrl.set_brightness(brightness... |
12,516 | 1f542986b06dfe90987e5fb33d6be4dae460e6e5 | """
MODEL
"""
from system.core.model import Model
class Product(Model):
def __init__(self):
super(Product, self).__init__()
def get_all_products(self):
return self.db.query_db("SELECT * FROM products ORDER BY created_at DESC")
def add_product(self, product):
query = "INSERT INTO ... |
12,517 | 9a25fe77691538ec15311021f54b4d48996fc24f | import requests
import json
from bs4 import BeautifulSoup
import time
url = 'https://kantan.vn/postrequest.ashx'
headers= {'content-type': "application/x-www-form-urlencoded", "accept": "*/*"}
data = {
'm': 'dictionary',
'fn': 'kanji_detail',
}
column_title_map = {
'ý nghĩa': 'mean',
'giải thích': '... |
12,518 | 56d9bc24789139292f4dc08edf656544a05de0d1 | from django.db import connection, transaction, utils
from core.utils.transform import from_dict_list_to_gen, from_csv_file_to_gen
from core.utils.csv_helpers import gen_to_csv
from django.conf import settings
from postgres_copy import CopyManager
from io import StringIO
import itertools
import csv
import random
impor... |
12,519 | 8dc998e73a58ec1e1e41163e107e020ae7209419 | #!/usr/bin/env python3
"""
Calculate gene lengths for each gene from an annotation
"""
__author__ = "Scott Teresi"
import argparse
import os
import numpy as np
import pandas as pd
import sys
from gene_lengths import import_genes
from count_matrix import import_count_matrix
from fpkm import calc_fpkm
def process... |
12,520 | c3327320e2500058ce587752752b906c26a23a39 | """
Configuration file for the application, sets key parameters
Variables denotes with (*) at the end of the corresponding comment must be set before running the program
"""
from common import secrets
import logging, os
# REQUIRED
DATA_PATH = '/home/martmichals/stockwatch/app/data/' # Path for data folde... |
12,521 | 24951f807ec2a7747bb3f7cf04ffd6f93c4920b2 | #################################
# Twitter Wiggler: Twitter Plays With Bug The Cat
# v1.0
# python3 <--- remember that for print statements!
# Nadine Lessio and Bijun Chen
#
# Some Limitations:
# --> This only works if your account is public
#################################
### IMPORTS #############################... |
12,522 | acbb4b1a27da30337fe6b382412722db63ff1095 | try:
import cv2
_available = True
except ImportError:
_available = False
def resize(x, output_shape):
"""Resize image to match the given shape.
A bilinear interpolation is used for resizing.
Args:
x (~numpy.ndarray): array to be transformed. This is in CHW format.
output_sha... |
12,523 | 8c8703a91657e8a9a4c78a96dd4ff7f166cee3a3 | import random as r
class sim:
def __init__(self):
self._simclock = None
self.t_arrival = self.g_packet()
self.t_depart = float('inf')
self.t_service = 0
self._maxque = None
self.cqs = 0
self.sstatus = 0
self.nodes = None
self.npdrop = 0
... |
12,524 | fab9eee98d580491419eb50c6a58befed29be431 | from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
class Review(models.Model):
product = models.ForeignKey('products.Product', null=True, blank=True, on_delete=models.SET_NULL)
review_rating = models.IntegerField(validators=[MinValueValidator(0), MaxValueValid... |
12,525 | 9048a7e18ecec0f2ac2334af017db6b12e2c4616 | from rest_framework import serializers
from ..models import Models, Trim, ModelsShown, Accessories, Location, Colours, Interiors, Engines, Gallery, Transmissions, Features, InteriorColour, ExteriorColour
class TransmissionsSerializer(serializers.ModelSerializer):
class Meta:
model = Transmissions
... |
12,526 | cef53e2254e0d07531d05d83aaeb0cbea3cc5d29 | import contextlib
from typing import Dict
from urllib.parse import urlparse
from azure.identity import ClientSecretCredential
from chaoslib.exceptions import InterruptExecution
@contextlib.contextmanager
def auth(secrets: Dict) -> ClientSecretCredential:
"""
Create Azure authentication client from a provided... |
12,527 | c4f0515daeb2d114a146550adf50a68c04e9bd10 | from elixir import *
from models.medline import *
import time, datetime
import pprint
import networkx as nx
import numpy
import itertools
metadata.bind = 'mysql+oursql://caopsci:G@localhost/medline'
setup_all()
level = 3
for year in range(1987,2014):
start = datetime.datetime(year,1,1)
end = datetime.da... |
12,528 | 37622f64569bfa998980a3ac8a8358a1c1c6728c | """
NT2 Kombinacio
Mester / Halado / Kombinatorikai algoritmusok / 48. Kombinacio
"""
from sys import stdin, stdout
n,m = tuple(map(int,stdin.readline()[:-1].split(" ")))
A = list(map(int,stdin.readline()[:-1].split(" ")))
Aprev = A[:]
if m==n:
for i in range(m):
stdout.write("{} ".form... |
12,529 | 14c2c9b6ff63ec66a44806cb14813f20e3c09947 | import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
import sys
from scipy.ndimage import rotate
'''
dat=fits.open('psf1.fits')
#21theta 21phi 5energies 1defocus 256x256 pixels
image=dat[0].data[10][20][1][0]
plt.imshow(image,origin='lower')
plt.show()
sys.exit()
fig = plt.figure(figsize=(21... |
12,530 | 4834b72efa37039d04033b5ff6cc1d3f02508f20 | from __future__ import unicode_literals
from django.db import models
class User(models.Model):
name = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add = True)
admin = models.IntegerField(default = 0)
rank = models.IntegerField(default = 0)
rank_amrap = models.IntegerF... |
12,531 | 7cf5494b5f900d742bfbc61eaac15a6f803085aa |
import matplotlib.pyplot as plt
from sitka_highs_lows import highs as sitka_highs
from death_valley_highs_lows import highs as deathvalley_highs
from sitka_highs_lows import dates
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(dates, deathvalley_highs, c='red', alpha=0.5)
ax.plot(dates, sitka_hi... |
12,532 | f517920c93e06edcfbbf94782b709b01c608baab | #!/usr/bin/env python
#
#
# Main parser for PDDL - JOe's version (don't overwrite!)
# Written by Joseph Kim
from Problem import Problem
import ast
#==============================================================================
# MAIN
#==============================================================================
# R... |
12,533 | b5647487c8593ca45cf1bdbf1c8cef59ee79660a | import copy
import math
import torch
import torch.nn as nn
import numpy as np
from constants import *
import torch.nn.functional as F
from utils.model_utils import device, init_weights
def get_nll_criterion(reduction="sum"):
crit = nn.NLLLoss(reduction=reduction)
return crit
def get_bce_criterion(reduction=... |
12,534 | 9f3a46ee7e55435e16b387593a62f121d08a7356 | from flask.views import MethodView
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.app import app
from owner.utils.utils import OwnerActions
owner_bp = Blueprint('owner_bp', __name__, )
class OwnerList(MethodView):
decorators = [jwt_required,... |
12,535 | d11591c1494783ea7c03d4c77c5333a3ededcab3 |
#calss header
class _CLIMAX():
def __init__(self,):
self.name = "CLIMAX"
self.definitions = [u'the most important or exciting point in a story or situation, especially when this happens near the end: ', u'the highest point of sexual pleasure']
self.parents = []
self.childen = []
self.properties = []
se... |
12,536 | 7ebc8dcfe54f613c29c8bde87c2995e88377f9ea | #!/usr/bin/env python
# -*- coding:utf8 -*-
"""
for 迭代对象 in 对象:
循环体
#基本应用,进行数值循环
range(start, stop[, step]) -> range object
start:开始数值
stop:结束数值
step:步长
"""
'''
for i in range(1, 11, 2):
print(i, end=" ")
for i in range(1, 11):
print(i, end=" ")
print()
for i in range(11):
print(i, end=" ")
''... |
12,537 | 268ea278571eea680956a172c2dbd6c3eed9223d | #
# Copyright 2014 Grupo de Sistemas Inteligentes (GSI) DIT, UPM
#
# 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
#
# Unles... |
12,538 | a93876f46e8ccd91d9e6c1355b3e501066fe6906 | #! /usr/bin/env python2
import os
import sys
import psycopg2
DB_NAME = "news"
# 1. The most popular three articles of all time?
query1 = ("SELECT articles.title, count(*) AS counting_view FROM log"
",articles WHERE log.status = '200 OK' AND substr(log.path,10,100)"
"= articles.slug GROUP BY artic... |
12,539 | 64ae3b7803bcd299dca7aef6e6538f06e3e6a182 | # -*- coding: utf-8 -*-
# Tags constants
DATE_CLASSES_KEYWORDS = [
x.lower()
for x in [
"news_date",
"news-date-time",
"date",
"news-date",
"newslistdate",
"createdate",
"date_block",
"b_date",
"entry-date",
"pub_date",
"g-... |
12,540 | e20258a35189e593f37dee7c8a2754f0bb3d902f | from forumapp.models import Channel, Thread, Comment
from forumapp.tests import create_channel, create_thread, create_comment
from django.contrib.auth.models import User
|
12,541 | e2a010985c2673cdc35e9882064075002ecb72d6 | from lib2to3.fixer_base import BaseFix
class FixBadOrder(BaseFix):
order = "crazy"
|
12,542 | 52706010dcf8612342387c8560675c4eb70ca946 | import flatten_dict
import requests
import requests.exceptions
# from typing import Any, _VT, _KT
import ruamel.yaml as yaml
class FlatKeysDict(dict):
@staticmethod
def dot_reducer(k1, k2):
if k1 is None:
return k2
else:
return k1 + "." + k2
def __init__(self, dic... |
12,543 | b69c13e1b7b7383bc873fdddf017c9c8e65ab25f | import dask.dataframe as dd
import json
import pandas as pd
from pprint import pprint
from pandas.io.json import json_normalize
import time
import numpy as np
from itertools import repeat
import datetime, time
from datetime import datetime
from dateutil import relativedelta
import sklearn
import seaborn as sns
from tsl... |
12,544 | 7762206ee4c929c1c7db8a984d5e817d7eb2c48c | local_env = Environment() # initialize the environment
library = local_env.SharedLibrary(
target="chapter_one",
source=["src/chapter_one.cpp"],
CPPPATH=["src"])
main = local_env.Program(
target="chapter_one_driver",
source=["src/main.cpp"],
CPPPATH=["src"],
LIBS=[library],
LIBPATH=["sr... |
12,545 | 5e76e8aaf3d92c7b1e1c7b9d4149b61085be13f2 | # coding=utf-8
from __future__ import absolute_import, division, print_function, \
unicode_literals
def is_installed():
# type: () -> bool
"""
Returns whether the C extension is installed correctly.
"""
try:
# noinspection PyUnresolvedReferences
from ccurl import Curl as CCurl
except ImportError... |
12,546 | 4bb12ea70ddf168bfa914e3771dcdd54edaba0b3 | from django.contrib import admin
from .models import Order, OrderDetail, Product, Student, ClassModel, Skill, Subject, SubjectRegistration, Profile
from students import models
# Register your models here.
class StudentAdmin(admin.ModelAdmin):
# fields = ['name', 'gender', 'address', 'student_code', 'class_model']... |
12,547 | 7ac0bccb9cc66b9a3c830007d47f4ff216b7ee23 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-04-04 08:14
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0042_auto_20160403_0931'),
('blog', '0009_userprofile_website'),
]
operations... |
12,548 | c3de87544f48f9b5cf22722f9cac552a43a242be | #!/usr/bin/env python3
"""Computes the proportions of mellizas and invariantly diacriticized tokens in a corpus."""
import argparse
import itertools
import os
from tqdm import tqdm
import unidecode
import diacriticize
if __name__=='__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.a... |
12,549 | 939768ba44afdf271ab9a7080b5dda1f45bb0699 | from MathUtills import integerdivide
from numba import int32, float32, boolean, short, int64
#from FaceNormal import FaceNormal
import numpy as np
import math
from MathUtills import integerdivide
import numba
from Graphics3D import method2798, method2799
from numba.experimental import jitclass
from expModel import Mod... |
12,550 | 8ae4a3c85b426f67e0f0d32b9256e4f424ca03b8 | #!/usr/bin/env python
import json
import argparse
import datetime
import os
from filters import valid_json_filter
from functools import partial
from pyspark import SparkContext, SparkConf
def rmkey(k, o):
if k in o:
del o[k]
return o
def extractKeys(keys, o):
rtn = {}
for k in keys:
i... |
12,551 | c0788353657db6ef8b923770243bec5de01d9ebc | import os
from collections import deque
import requests
from flask import Response
from .constants import PROGRAMS_BASE_URL
def send_health_update():
url = f'{os.getenv("WEB_BASE_URL")}/node-health'
res = requests.post(url)
if res.status_code == 200:
return {'Result': 'Successfully updated node up-... |
12,552 | 90f31c4ca0aba01736ff4e62ec41896456bf312b | import random
class Patient(object):
def __init__(self, name, allergies):
self.id = random.randint(1, 10000)
self.name = name
self.allergies = allergies
self.bed_number = None
class Hospital(object):
def __init__(self, name):
self.patients = []
self.name = name... |
12,553 | 6d8694b74f0da666d2960f607634e1fea96d30bd | def binarySearch(lista,target):
low=0
high=len(lista)
count=0
while low<=high:
mid=(high+low)//2
if mid<0 or mid >len(lista)-1:
return False,count
if lista[mid]==target:
return True ,mid,count
else:
if lista[mid]>target:
... |
12,554 | 6a8c26e35a93052b603b687e17d772f1a1061348 | from django.http import HttpResponse
from django.shortcuts import render,get_object_or_404
from django.shortcuts import redirect
from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth import login
from .forms import ContactForm
from requests.models import Requests
def home_page(request):... |
12,555 | 65af86ec82d641df9aa2096d917cc7f371a4bbc7 | import allure
import pytest
class TestSetting:
@allure.severity("blocker")
@allure.step(title="用于测试“XXX”功能的测试脚本")
def test_login1(self):
print("");
assert 1
@allure.severity("critical")
@allure.step(title="用于测试“XXXX”功能的测试脚本")
def test_login2(self):
print("");
a... |
12,556 | 276c4b699fe7e78bf1f5e6d659512ac9ba3ed58d | import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split, cross_validate
import dill
def main(N=3, save=True, verbose=False):
data_df = pd.read_csv('data/training_data_%d_years.csv' % N)
N_CATS = int(len... |
12,557 | 5eaa469a4d79b251f55b8f982d38a131284592c2 | #!/usr/bin/env python
from __future__ import print_function, unicode_literals
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('num_chapters', type=int)
args = parser.parse_args()
task_templates = [
"read chapter {}",
"make chapter summary for chapter {}",
"make flashcards for chapte... |
12,558 | c94e87b789eea19deb6641b23ad6a93fb50503b3 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-26 15:49
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... |
12,559 | fb71e8a07725bd501715fae09e9a8ac5709a6411 | import sys
n = int(raw_input('enter number:'))
s = '#'
for i in range( 1 , n+1):
print " "*(n-i) + s*i |
12,560 | 0beabf756f471d80313e7d2d93d2e76ee65c0fd6 | from collections import defaultdict
# from torchtext.vocab import Vocab
from torch.utils.data.dataset import Dataset, TensorDataset
from pathlib import Path
from collections import Counter
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as opt... |
12,561 | db205c38ec2209d444d04c73fa021b6651031744 | """
This module provides 1/2-D FFTs for functions taken on the interval
n = [-N/2, ..., N/2-1] in all transformed directions. This is accomplished
quickly by making a change of variables in the DFT expression, leading to
multiplication of exp(+/-jPIk) * DFT{exp(+/-jPIn) * [n]}. Take notice that
BOTH your input and outp... |
12,562 | f55a56700316efe55270afc741a351ce8ab1f0ed | import pandas as pd
import numpy as np
af_df = pd.read_csv('Milk_2/AF_score/af_raw_data.csv')
af_df = (af_df
.groupby(['to_user'])
.agg({'AF score': 'mean', 'fid':'count'})
.reset_index()
.sort_values(['AF score'], ascending=False)
.rename({'to_user': 'from_user', 'fid': '... |
12,563 | a1b132633181aa2037eba87db98f53f8eaccbcd0 | #%%
"""
Created on 08 Mar 2019
Pathwise estimation for delta and vega for the Black-Scholes model
@author: Lech A. Grzelak
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as st
import enum
# This class defines puts and calls
class OptionType(enum.Enum):
CALL = 1.0
P... |
12,564 | 0e57ca4f6620491060ea712738448fcaad6e176f | import pytest
from src.zadanie_kalkulator import ZadanieKalkulator
class TestZadanieKalkulator():
@pytest.fixture()
def return_kalkulator(self):
return ZadanieKalkulator(4,5)
@pytest.fixture()
def return_kalkulator2(self):
return ZadanieKalkulator(6,7)
def test_dodaj(self, return... |
12,565 | fb07bd7674f623acc201b29269eb0e773338385a | x = True
y = False
z = False
if not x or y:
print(1)
elif not x or not y and z:
print(2)
elif not x or y or not y and x:
print(3)
else:
print(4) |
12,566 | 5511361ba73f8739f4900083c0fdf7fa298c423b | """
对时间处理的模块
time
"""
import time
# 1. 人的时间:2020年10月27日 09:30
# 时间元组:年,月,日,时,分,秒,星期,年的第几天,夏令时
tuple_time = time.localtime()
print(tuple_time[0]) # 获取年
print(tuple_time[-3]) # 获取星期
print(tuple_time[3: 6]) # 获取时分秒
# 2. 机器时间:
# 时间戳:从1970年元旦到现在经过的秒数
print(time.time()) # 1603762810.9457989
# 3. 时间元组 <---> 时间... |
12,567 | 44e1a16a97bfc253815c17d6abe79e441d035da3 | import math
#计算两点之间距离是否小于r
def distanceInR(cx,cy,r,x,y):
dist=math.sqrt((math.pow(x-cx,2)+math.pow(y-cy,2)))
if dist<r:
return True
else:
return False
def distanceCal(cx,cy,x,y):
dist=math.sqrt((math.pow(x-cx,2)+math.pow(y-cy,2)))
return dist
|
12,568 | 67bb622ebc8cef0ba8d1ea1834897c109d764601 | # -*- coding: utf-8 -*-
import os.path
import re
import warnings
# Ugh, pip 10 is backward incompatible, but there is a workaround:
# Thanks Stack Overflow https://stackoverflow.com/a/49867265
try: # for pip >= 10
from pip._internal.req import parse_requirements
except ImportError: # for pip <= 9.0.3
from pip.... |
12,569 | 7338a76fae44463bb2f33c6ae2ddcc6c20315d86 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import pymysql
def conn():
# Criar um arquivo setup.txt com os parametros de conexao divididos por
# espaço
arquivo = open('setup.txt', 'r')
leitor = arquivo.read()
parametros = leitor.split()
db = pymysql.connect(host=parametros[0],
... |
12,570 | de2ba2b5dc3836abad9f97c8482b62fbc1e64383 | #!/usr/bin/env python
"""Test gs-wrap cp many to many live."""
# pylint: disable=missing-docstring
# pylint: disable=too-many-lines
# pylint: disable=protected-access
# pylint: disable=expression-not-assigned
import pathlib
import tempfile
import unittest
import uuid
from typing import List, Sequence, Tuple, Union #... |
12,571 | 1c83f81993310c86dccdb8fc266c0195716dfa35 | from PIL import Image
img = Image.open('C:\\Users\\Matt\\codeguild\\javascript\\mole.png')
roated_image = img.rotate(45).save('rotated.png')
|
12,572 | 4aec64ef6a540973a3d87392a4c9a6a26a75422b | from django.shortcuts import render_to_response, redirect
from models import *
from django.db.models import Q
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def index(request, ):
cats = Comcat1.objects.all().order_by('-search_rank')[:3]
coms = Co... |
12,573 | 70c263591f0e76ce956d97a6d167a3ba364ae223 | # Time Conversion
def timeConversion(s):
""" Converts to military (24-hour) time """
new_s = ''
if s[-2:] == 'PM' and s[:2] != '12':
new_s = str(int(s[:2]) + 12) + s[2:-2]
elif s[-2:] == 'AM' and s[:2] == '12':
new_s = '0' + str(int(s[:2]) - 12) + s[2:-2]
else:
new_s = s[:-2... |
12,574 | 0d2ae5ab3e8af42f8cf8f67a98b961d0cb85515f | from django.contrib import admin
from api.models import Tag, Category, Post
@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
list_display = ['name']
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ['name']
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
... |
12,575 | f27cbf4448225edf3778c04537a7ceb4a65542ef | import numpy as np
# hyper parameter
learning_rate = 0.01
np.random.seed(777) # for reproducibility
# Training Data
train_X = np.asarray([3.3, 4.4, 5.5, 6.71, 6.93, 4.168, 9.779, 6.182, 7.59, 2.167,
7.042, 10.791, 5.313, 7.997, 5.654, 9.27, 3.1])
train_Y = np.asarray([1.7, 2.76, 2.09, 3.19, 1.694... |
12,576 | 3ff8458fa1961cdcf1ec219d58d8bd46363e4fac | from django.db import models
from django.contrib.auth.models import User
import os
# Create your models here.
def get_image_path(instance, filename):
return os.path.join('photos', str(instance.id), filename)
class Club(models.Model):
club_name = models.CharField( max_length = 100)
player_name = models.Cha... |
12,577 | b91355ed62bfd34351d67eef560ba8a85baa82b0 | from importlib import import_module
import numpy as np
import pytest
from armory.data import datasets
from armory.utils import external_repo
from armory.utils.config_loading import load_dataset
from armory.data.utils import maybe_download_weights_from_s3
from armory import paths
from armory.utils.metrics import objec... |
12,578 | 823080ee874427a5901558f707f4ca2bf927a869 |
import requests
from pprint import pprint
import config
import logging
from aiogram import Bot, Dispatcher, executor, types
from aiogram.dispatcher import FSMContext
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher.filters.state import State, StatesGroup
def func1(tag... |
12,579 | 21f82801b5d324d0aac073dfc36a691a4d92e687 | import math
Radians60 = math.radians(60)
sin60 = math.sin(Radians60)
sin60Rounded = round(sin60,2)
Radians90 = math.radians(90)
tan90 = math.tan(Radians90)
tan90Rounded = round(tan90,2)
print("Sin60:{}".format(sin60Rounded))
print("tan90:{}".format(tan90Rounded)) |
12,580 | 929232be7b0eb0faff26c3b126b3e451dbb63afa | from django.db import models
#from django.contrib.auth.models import User
class Persona(models.Model):
nombres = models.CharField(max_length=255)
apellidos = models.CharField(max_length=255)
cedula = models.CharField(max_length=255)
sexo = models.CharField(max_length=1)
telefono_convencional =... |
12,581 | 07aeea887f2193c4055c813b31446fbb733e8393 | from django.shortcuts import render
from ..models import Site
from django.core.paginator import Paginator, EmptyPage
from copy import deepcopy
from django.db.models import Avg
def embed_sites(request):
search_request_dict = deepcopy(request.GET)
# 如果沒輸入page,預設值=1
if request.method == 'GET' and 'page' in reque... |
12,582 | ee29f01c92262a84a3860b224eceb9eed1cd4a94 | """
**********************************************************
* Main thread that runs the IoT Doorbell application *
**********************************************************
Main thread runs the Application and links all the features of the doorbell together
Switch face check On/Off
Run ... |
12,583 | 8dfd02840706455f17a215deac6cda4db5747407 | import base64
source_file = open("data.txt", "r")
contents = source_file.read()
decoded = base64.b64decode(contents)
print(decoded.decode())
#decoded_file = open("data_decoded.txt", "w")
#decoded_file.write(decoded)
#decoded_file.close() |
12,584 | 4db98722a9901d1de190232c83f016ab555f59dc | # coding: utf- 8
def title(titl):
print('\n'+'>' * 10 + titl + '<' * 10)
title( ' bool ')
a = True
b = False
print( a )
print( b )
print( type(a) )
print( type(b) )
print( 1 == 1)
print( 2 > 1 )
print( 2 < 1 ) |
12,585 | 15557d5638783a874a2733ec5998eaed808c0cd7 | '''
递归:一个函数在自己函数内部调用自己。
循环
'''
num = 5
def func():
global num
if num == 0:
return 0
else:
print("12345")
num -= 1
func()
func()
# 复习递归遍历目录
|
12,586 | 423a29ca544ae7a41a362e7d80d1f5c61d7b3a69 | """
Tests for tasking exceptions
"""
import os
import zipfile
from django.test import TestCase, override_settings
from tasking.common_tags import (
MISSING_FILE,
NO_SHAPEFILE,
TARGET_DOES_NOT_EXIST,
UNNECESSARY_FILE,
)
from tasking.exceptions import (
MissingFiles,
ShapeFileNotFound,
Targe... |
12,587 | 367d794fa185906b29d457bbe7f77ac9c17cf0ae | import numpy as np
a = np.array((
[1,2,3],
[4,5,6]
))
print('matrix a dengan ukuran', a.shape)
print('matrix a:')
print(a)
# transpose matrix 3 cara
print('transpose matrix dari a:')
print(a.transpose())
print(np.transpose(a))
print(a.T)
# flatten array, -- > vector baris
print('flatten matrix a:')
print(a... |
12,588 | 620d0dbbdaec080e71a2207379320a65f4b2d64f | #!/usr/bin/env python3
from os import path
from networkx import DiGraph, topological_sort
def main():
with open(path.join(path.dirname(__file__), "input.txt")) as f:
g = DiGraph()
for line in f:
line = line.strip()
parts = line.split()
if parts[0] == "value":
... |
12,589 | d70497ea71613df12fd1b3434bc3111bc40678dd | from data_proc.DataGeneratorCelebA import DataGeneratorCelebA
from data_proc.DataGeneratorCelebASparse import create_map
from data_proc.DataGeneratorWiki import load_config_wiki
from data_proc.ConfigLoaderCelebA import load_attr_vals_txts, load_atributes_txts
import numpy as np
from keras.preprocessing import image
fr... |
12,590 | 418685850c39bd9a008ade082cac962a92704c94 | """
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
from collections import defaultdict
def c... |
12,591 | ab4162c6034ad51fbd2c4d93150bd9cded8f8d1b | # -*- coding: utf-8 -*-
#import json
#import urllib
import logging
import datetime
import traceback
from lib import error_codes
#from terminal_base import terminal_commands
import pymongo
#from tornado.web import asynchronous
from tornado import gen
from helper_handler import HelperHandler
from lib import utils
#from ... |
12,592 | 61686a9e3f6e6f9a0606cd66cc15679f079973f2 | """
All constants used for dialysis project
accumulated in one file for easier accessibility
and cleaner code.
"""
# Window settings and all colors used in project
WINDOW_TITLE = "Dialysis Nutrition Information By Yihan Ye"
MAIN_WINDOW_SIZE = "1000x1000"
MAIN_WINDOW_COLOR = "#bedddc"
MAIN_FRAME_COLOR = "#f4efeb"
GOOD... |
12,593 | 94d8fcfa9e46a398ff225ad6f5dd5ecdc2f351ab | import OpenGL
OpenGL.ERROR_CHECKING = False
from OpenGL.GL import *
def line_strip( vertex_list, color_list = None ):
glBegin(GL_LINE_STRIP)
for i, v in enumerate(vertex_list):
if color_list:
glColor( color_list[i] )
glVertex( v )
glEnd()
def line( start, end ):
glBegin(G... |
12,594 | f92ae19bfe698db836b6a9907b2c1b8e47484032 | import discord
from discord.ext import commands, tasks
from discord.ext.commands import errors
from discord.utils import get
import os, requests, json
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('TOKEN')
# Defining main variables
BOT_PREFIX = str(os.getenv('BOT_PREFIX'))
OwnerID = int(os.getenv('O... |
12,595 | 62a84d70fd3e4c7b77bdb6f9290c9ef0752d4030 | # requires Python 3.7+
import sys
import asyncio
loop = asyncio.get_event_loop()
async def example_01():
print("Start example_01 coroutine.")
await asyncio.sleep(1)
print("Finish example_01 coroutine.")
async def example_02():
print("Start example_02 coroutine.")
await asyncio.sleep(1)
pri... |
12,596 | f82ab747a4dbd38beea6fca7a2cacaaf09fd2b3f | import xml.etree.cElementTree as ET
import re
import datetime
from collections import Counter
tmp = ''
prev = '' #if xml ordered by date, we can get the next result and keep track of max
total = 0 #most common date so far for grsphing thory
prevTotal = 0 #the previous dates maximum, for graph theory matches
maxGtDat... |
12,597 | 721920e442b3dd07cc79bbdce9d65ba078634754 | # ------------------------------
# 670. Maximum Swap
#
# Description:
# Given a non-negative integer, you could swap two digits at most once to get the
# maximum valued number. Return the maximum valued number you could get.
#
# Example 1:
# Input: 2736
# Output: 7236
# Explanation: Swap the number 2 and the number ... |
12,598 | 0bd190452fe573cab9fd1bf678c1134cc91c7ec8 | import sys
import os
sys.path.insert(0, '../oscar.py')
import re
from oscar import Project
from oscar import Time_project_info as Proj
import subprocess
from time import time as current_time
start_time = current_time()
def bash(command):
proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
(out, er... |
12,599 | 78c6a0052fb2b61e4a669966907011746862d4e3 | import datetime
import pytz
import web
import config
db = web.database(dbn='sqlite', db='dp.sqlite')
# =================================================================
# datetime
def current_time():
return datetime.datetime.now(pytz.utc)
def local_time():
return datetime.datetime.now(config.tz)
def in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.