index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
8,200 | 610fde0db6e3fe0a54a008287e0c36b25b7a482f | from __future__ import division
__author__ = 'Vladimir Iglovikov'
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import numpy as np
from sklearn.cross_validation import ShuffleSplit
from sklearn.metrics import mean_squared_error
import math
from sklearn.ensemble import RandomForestRegressor
joined... |
8,201 | a8cf8d0965cb877d50cee403fbc30f27484f4f36 | import torch
import torch.nn as nn
class DehazeNet(nn.Module):
def __init__(self, input=16, groups=4):
super(DehazeNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=5)
self.relu1 = nn.ReLU()
self.conv2 = nn.Conv2d(in_channels=4, out_channels=... |
8,202 | 5a092150896e4082431849828793f86adcd2211c | LOGIN_USERNAME = 'YOUR_USERNAME'
LOGIN_PASSWORD = 'YOUR_PASSWORD' |
8,203 | 8488fdd216c30c3cb4b0060305af6708d890bc86 | #!/usr/bin/env python
# coding: utf-8
# # PyCity School Analysis
# 1. Charter school types show better performace than District School types in all the scores.
# 2. Overall students are performing better in english between (80 to 84%), than math (76 to 84%)
# ### Note
# * Instructions have been included for each seg... |
8,204 | caac9dfc7d52607c2af67ddc03a3a7bdae9911bb | #coding=utf-8
'''
Created on 04/09/2012
@author: Johnny
'''
from ckeditor.widgets import CKEditorWidget
from django.conf.urls import patterns, url
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.templatetags.static import static
import views
from portfolio.models ... |
8,205 | 775900d4c059c89bfb10f5c3c2a924a41a049438 | import time
import numpy as np
import matplotlib.pyplot as plt
class stochasticGradient :
def __init__( self , kwargs ) :
self.inputVectors = kwargs["inputVectors"]
self.expectedOutput = kwargs["expectedOutput"]
self.noOfEpochs = kwargs["noO... |
8,206 | 5cc18af40befab444df44bf3da1f0175e5d18983 | import datetime
import shutil
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
from dataclasses import dataclass
PATH_TO_TEMPLATES = Path('TEMPLATES/')
PATH_TO_RESOURCES = Path('RESOURCES/')
PATH_TO_OUTPUT = Path('../docs/')
URL_ROOT = "https://katys.cz/"
link_to_homepage = "/" # TODO: alwa... |
8,207 | 1e344330b88b336598295e2a7be6a6dc57cb3d59 | # -*- encoding: utf-8 -*-
import requests
import time
import random
STATS = True
INFINITE = True
VOTING_ENDPOINT = 'http://www.adressa.no/poll/vote.do'
# These are the required fields from the voting form
payload = {
"vote": "svar4",
"mentometerId": "10790638",
"publicationId": "167",
"redirectTo": "... |
8,208 | 43d5bf79f16e8530797cdd13cdfcc91f0d3aef5e | import sys
import numpy as np
sys.setrecursionlimit(10 ** 7)
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N, M = map(int, input().split())
def cumprod(arr, MOD):
L = len(arr)
Lsq = int(L ** 0.5 + 1)
arr = np.resize(arr, Lsq ** 2).reshape(Lsq, ... |
8,209 | 647aa37c53aac7c620e5095c7a9368f4ad038608 | import serial, time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.OUT)
GPIO.setup(17, GPIO.OUT)
GPIO.setup(27, GPIO.OUT)
GPIO.setup(22, GPIO.OUT)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)
GPIO.setup(7, GPIO.OUT)
pwm1 = GPIO.PWM(23,100)
pwm2 = GPIO.PWM(24,100)
pwm1.start(100)
pwm2.start(100... |
8,210 | 22706d7d9c04bb660c9bf0df66de89ed6bd480c2 | class Solution:
def minWindow(self, s: str, t: str) -> str:
char_cnt = {}
for character in t:
if character not in char_cnt:
char_cnt[character] = 1
else:
char_cnt[character] += 1
dq = [] # add index & character
min_substring = ... |
8,211 | f652fa6720582d50f57f04d82fb2f5af17859ebd | # Mac File
import platform
import os
def Mac(SystemArray = [], ProcessorArray = []):
# System Info
OSName = str()
OSVersionMajor = str()
OSArchitecture = str()
# Processor Info
command = '/usr/sbin/sysctl -n machdep.cpu.brand_string'
ProcInfo = os.popen(command).read().strip()
ProcNam... |
8,212 | 9f831b8c90dd428879319b63712bd03fcc01b631 | # The purpose of this bot is to cick the first black pixel.
# Testing a change here done by Git.
# changes through branches
import pyautogui
import keyboard
import win32api
import win32con
import time
# click function, with a 0.01 pause inorder to properly run the script
def click(x, y):
win32api... |
8,213 | aa515b1b919eb557cd8c7e5f4d22773980b5af96 | # -*- coding: utf-8 -*-
import datetime
from unittest.mock import patch
from odoo.tests import common
import odoo
from .common import RunbotCase
class TestSchedule(RunbotCase):
def setUp(self):
# entering test mode to avoid that the _schedule method commits records
registry = odoo.registry()
... |
8,214 | dfcb095b26a21ba0c8ccc2a2c664bcfab29b8351 |
"""
All requests will be sent to backend as:
{
name: <class name>,
data: {
<all instance variables>
}
}
"""
class NewDriver:
def __init__(self, uri, authToken):
self.uri = uri
self.authorizationToken = authToken
class DriverClose:
def __init__(self... |
8,215 | 88a3c3fad9717675ed13bcbc778d635f6552c4b1 |
from PySide.QtCore import (qAbs, QLineF, QPointF, qrand, QRectF, QSizeF, qsrand,
Qt, QTime,QSettings,QSize,QPoint)
from PySide.QtGui import (QBrush, QKeySequence, QColor, QLinearGradient, QPainter,
QPainterPath, QPen, QPolygonF, QRadialGradient, QApplication, QGraphicsItem, QGraphicsScene,
QGra... |
8,216 | 41a80feeb1fdc8ad783706ad261f5fc1124371d6 | """
Solution to Codeforces problem 50A
Copyright (c) GeneralMing. All rights reserved.
https://github.com/GeneralMing/codeforces
"""
n = input().split()
n[0] = int(n[0])
n[1] = int(n[1])
print((n[0]*n[1])//2) |
8,217 | 6b2161379bdd27980d3a515cdf4719ab036845fe | #!/usr/bin/env python
# coding: utf-8
# In[5]:
import re
def phonenumbervalidate(phone):
pattern ='^[6-9][0-9]{9}$'
phone =str(phone)
if re.match(pattern,phone):
return True
return False
print(phonenumbervalidate(998855451))
print(phonenumbervalidate(9955441))
# In[10]:
import re
def pho... |
8,218 | eb4bc008b7e68f8a6e80e837fa970d77a5ed3547 | import pandas as pd
import numpy as np
import random
import copy
class Node(object):
'''
Defines a Node Class for storing characteristics and CPT of each node
'''
def __init__(self,name):
self.parents = []
self.children = []
self.name = name
self.cpt=[]
self... |
8,219 | faebefcadbc184fab29deb2988089223a8f09e7e | nome = str(input('Digite um nome completo: ')).lower()
silva = 'silva' in nome
if silva == True:
print('Existe Silva nesse nome')
else:
print('Não há Silva nesse nome') |
8,220 | 049d83bc1a31ef170654fda47d1f58e024befb44 | # Generated by Django 3.0.4 on 2021-03-27 19:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('electra', '0009_remove_response_img'),
]
operations = [
migrations.AddField(
model_name='response',
name='date_time'... |
8,221 | e983db4b99e73929c02eb84fab1ee56138048052 | from django.shortcuts import render, redirect
from django.contrib import messages
from .models import *
from django.views.decorators.csrf import csrf_exempt
def index(request):
notes = Note.objects.all().order_by('-created_at')
context = {
"notes" : notes
}
return render(request, 'notes/index.h... |
8,222 | b2fb5564d44f7481c6de2a5d4af09df4903026b8 | # user_events.py
import dataclasses
from typing import Optional
@dataclasses.dataclass
class UserUpdateMessage:
id: str
name: Optional[str] = None
age: Optional[int] = None
async def receive_user_update(message: UserUpdateMessage) -> None:
print(f"Received update for user id={message.id}")
|
8,223 | d551cab1856fbdb91918f9171d5c02b8dab84aba | # coding=UTF-8
#!/usr/bin/env python
# for models.py
from django.db import models
from django.db.models import F, Q, Sum, Avg
from django.db import transaction
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.sites.models import Site
# from ... |
8,224 | 3cb3361e8777d31575d81d2a1191f137e4174492 | a = [1, 11, 21, 1211, 111221]
for i in range(30):
#next_num_list = []
next_num = ''
next_char = ''
step = 0
count = 0
# Analyze the string.
for char in str(a[i+4]):
if step == 0:
next_char = char
count += 1
step = 1
elif step == 1:
... |
8,225 | 10a981e35ce00ee8e32a613823d3bc919fafaae8 | import sqlite3
connection = sqlite3.connect("../db.sqlite3")
cursor = connection.cursor()
sql_file = open("sample.sql")
sql_as_string = sql_file.read()
cursor.executescript(sql_as_string)
for row in cursor.execute("SELECT * FROM results_states"):
print(row)
|
8,226 | 36c1d75171d772138b820651e11a3a7bc3a6521c | import unittest
from month import Month
class MonthUnitTests(unittest.TestCase):
def test_header(self):
cal = Month(5, 2012)
result = cal.header()
self.assertEqual(" May 2012", result)
def test_header_different_month(self):
cal = Month(3, 2012)
result = cal.header()
self.assertEqual(" March 20... |
8,227 | 4d059d1ca407ef60f1fbf9d8bead1cf45c90c28a | from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import get_object_or_404
from rest_framework import status, viewsets
from rest_framework.exceptions import PermissionDenied
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_f... |
8,228 | 9f3fcc6e097e37479e3ccf1385f20d70d7c3b6c7 | #! /usr/bin/python3
import pprint
import tkinter as tk
from tkinter import messagebox
from PIL import Image
from tkinter import *
from prettytable import PrettyTable
import ttk
import os
import subprocess
import mysql.connector
from datetime import datetime
import time
db=mysql.connector.connect(host='localhost',user... |
8,229 | 598a0771dd1447034f2db95c67dd0dcf968f43a7 | import bcrypt as bcrypt
from config.configuration import Configuration
class Usuario(Configuration.db.Model):
__tablename__ = "usuario"
id = Configuration.db.Column(Configuration.db.BIGINT, primary_key=True, autoincrement=True)
code = Configuration.db.Column(Configuration.db.String(80), unique=True, nul... |
8,230 | 228852f960e9343d9f45abdd3204cfab7bb54bc6 | """
* Team Id : LM#4787
* Author List : Arjun S, Vinod, Arvind, Vishnu
* Filename: ArenaPreprocessor.py
* Theme: Launch A Module
* Functions: arena_preprocess, getTransformationMatrix, get_robot_space
* Global Variables: None
"""
import cv2
import numpy as np
"""
* Function Name... |
8,231 | 16c4dbd472f9d32e5fa48a28dff4a40914f7d29e | from . import colorbar_artist
from . import subplot_artist
from . import surface_3d_with_shadows
from .colorbar_artist import *
from .subplot_artist import *
from .surface_3d_with_shadows import *
__all__ = [
'colorbar_artist',
'subplot_artist',
'surface_3d_with_shadows']
__all__.extend(colorbar_artist.__... |
8,232 | 55977a673bb36900e1d797cb9ec330ce6d9aa717 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import csv
file_open = open("C:/Users/DI_Lab/Desktop/20년도 Kisti 과제/HMM/HMM(Up,Down).csv", 'r', encoding='UTF8')
save_file = open("C:/Users/DI_Lab/Desktop/20년도 Kisti 과제/HMM/HMM사후확률.csv", 'w', encoding='UTF8',newline='')
write = csv.writer(save_file)... |
8,233 | 30a2358e8396d24d6c3cd72d04321aa9f9f83995 | import json
from week2.Stack import Stack
class TransactionStack:
def __init__(self):
self.stack = Stack()
with open("json_file/Transaction_Stack.json") as data:
try:
temp = json.load(data)
except Exception:
pass
else:
... |
8,234 | e3d886dedaf5b120392d0dc81c4c71398f08f8d6 | import numpy as np
import pandas as pd
import time
from sklearn.metrics import log_loss
from keras.models import Sequential, Model
from keras.layers import Dense, Input
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers import LSTM
from keras.layers.convolutional import Convolution3D
f... |
8,235 | 1ca20b0cd9217623ff039ab352acd09df8dfae1b | class Enumerator(object):
"""For Python we just wrap the iterator"""
def __init__(self, next):
self.iterator = next
def __next__(self):
return next(self.iterator)
# Python 2.7
next = __next__
def __iter__(self):
return self
|
8,236 | 8566e30a6450a72a0e441155321bd03363944b5a | import pymysql
db= pymysql.connect(host = 'localhost',
port = 3306,
user = 'root',
password = 'Wubaba950823',
database = 'mydb',
charset = 'utf8mb4'
)
# 使用cursor()方法获取操作游标
curso... |
8,237 | 7deaee28674c465694c348c21e87addbcc8ea923 | from pymongo import MongoClient
from datetime import datetime
import sys
import requests
import urllib
import json
import xml.etree.ElementTree as ET
import xmltodict
import pandas
from lxml import etree
from bson.json_util import dumps
bornTables = pandas.read_html("http://statis.moi.gov.tw/micst/stmain.jsp?sys=220&y... |
8,238 | a6cb7a134fb8480d344743bcb7bc8766146d256f | # Generated by Django 2.1.5 on 2019-01-21 22:51
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
8,239 | 632fdb95874f0beeb6d178788f7c7e7c9e8512e5 | a = 10
b = 20
c = a+b
d = b-a
print(c)
print(d) |
8,240 | a68de7555fdab06014fd562e7db29ca2da03f443 | # coding=utf-8
import re
import traceback
from pesto_common.config.configer import Configer
from pesto_common.log.logger_factory import LoggerFactory
from pesto_orm.core.base import db_config
from pesto_orm.core.executor import ExecutorFactory
from pesto_orm.core.model import BaseModel
from pesto_orm.core.repository i... |
8,241 | 92391f17380b2e09cc9b3913f15ce35189d9893d |
def check_integer(a):
if type(a) != int:
print("please input an integer")
exit()
def is_even(a):
check_integer(a)
if a % 2 == 0:
print("true")
return True
else:
print("false")
return False
is_even(2)
is_even(3)
is_even("cat")
|
8,242 | 520672f8607751b65fe9e4b975a9978ed0ab71b6 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the file entry implementation using pyfshfs."""
import unittest
from dfvfs.lib import definitions
from dfvfs.path import factory as path_spec_factory
from dfvfs.resolver import context
from dfvfs.vfs import hfs_attribute
from dfvfs.vfs import hfs_file_entry
f... |
8,243 | 1c13a9ca3617dc6f1a1f1aa8249cce37062a449b | #!/usr/bin/python
import xml.dom.minidom
import os
import matplotlib.pyplot as plt
import cPickle as p
import numpy as np
def modifyXML(name,numCar):
DOMTree = xml.dom.minidom.parse(name)
objects=DOMTree.getElementsByTagName('object')
for object in objects:
if object.getElementsByTagName('name')[0].childNodes[0].... |
8,244 | 6ad2014191215dac97ad6fc6a026512c3d1866dc | from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired
from flask_wtf import FlaskForm
# ...
class LoginForm(FlaskForm):
"""登录表单类"""
username = StringField('用户名', validators=[DataRequired()])
password = PasswordField('密码', validators=[DataRequired()]) |
8,245 | f7d487ec99e2fa901677ab9aec0760a396722e12 | """
*********************************************************************
* Project : POP1 (Practical Exam)
* Program name : q2.py
* Author : varunk01
* Purpose : Attempts to solve the question 2 from the exam paper
* Date created : 28/05/2018
*
* Date Author Ver Comment
* 28/05/2018 varunk... |
8,246 | 4eb7abb24451f3f895d0731de7b29a85d90c1539 | from flask import Blueprint, request
from ecdsa import SigningKey, NIST384p
import base64, codecs
from cryptography.fernet import Fernet
ecdsa_app = Blueprint('ecdsa_app', __name__, url_prefix='/ecdsa_app')
f = Fernet(Fernet.generate_key())
sk = SigningKey.generate(curve=NIST384p)
vk = sk.get_verifying_key()
@ecd... |
8,247 | ce28462621a423c6661c672cf92d7e9c91875cfa | """
Copyright (C) 2018-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... |
8,248 | be238268b9fdd565f3cb0770839789b702940ef9 | #!/usr/bin/env python
# This file just executes its arguments, except that also adds OUT_DIR to the
# environ. This is for compatibility with cargo.
import subprocess
import sys
import os
os.environ["OUT_DIR"] = os.path.abspath(".")
assert os.path.isdir(os.environ["OUT_DIR"])
sys.exit(subprocess.call(sys.argv[1:], env... |
8,249 | f6846bfc6c4d803cedaf37e079e01188733938c7 | #!/usr/bin/env python3
import collections
import glob
import os
import pandas as pd
import numpy as np
import torch.nn.functional as F
import PIL.Image as Image
from inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params
from inference.metrics.fid.fid_score import _compute_... |
8,250 | 0074b0cd1e4317e36ef4a41f8179464c2ec6c197 | rf = open('A-large.in', 'r')
wf = open('A-large.out', 'w')
cases = int(rf.readline())
for case in range(1, cases + 1):
digits = [False] * 10
n = int(rf.readline())
if n == 0:
wf.write('Case #%s: INSOMNIA\n' % case)
continue
for i in range(1, 999999):
cur = n * i
for c in str(cur):
digits[int(c)] = True... |
8,251 | a2a3e8d52fd467178460b178c5dbf9ccd72706e7 | pokerAssignments = {'2': 20, '3': 30, '4': 40, '5': 50, '6': 60, '7': 70, '8': 80, '9': 90, 'T': 100, 'J': 110, 'Q': 120, 'K': 130, 'A': 140, 'C': 0, 'S': 1, 'H': 2, 'D': 3} #Used to assign each card to a unique three-digit integer
configScoring = {(1, 1): 0, (1, 2): 1, (2, 2): 2, (1, 3): 3, (2, 3): 6, (1, 4): 7} #Tra... |
8,252 | 245e407c9e92b3ac34389a48fcef4fc1b349ea18 | from rest_framework import generics
from animals.models import Location
from animals.serializers import LocationSerializer
class LocationList(generics.ListCreateAPIView):
queryset = Location.objects.all()
serializer_class = LocationSerializer
name = 'location-list'
class LocationDetail(generics.Retriev... |
8,253 | 591b1a2e245ae0f3c9b2a81769bbf5988574ed07 | #!/usr/bin/env python3
import math
from PIL import Image as Image
# NO ADDITIONAL IMPORTS ALLOWED!
def in_bound(dim , s):
"""Get inbound pixel coordinate for out-of-bound
Args:
dim (int): Image height or width
s (int): Coordinate
Returns:
int: Inbound
"""
if s <= -1:
... |
8,254 | dc3a3f5675860792ecfa7dcd5180402d89b669b1 | # -*-coding:utf-8-*-
import os
import time
import shutil
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--dir', type=str, required=True)
parser.add_argument('--task', type=str, required=True)
args = parser.parse_args()
if not os.path.exists(args... |
8,255 | c2ee716b72652035502a1f07dfe8aa68a104b2bb | import numpy as np
import os
# ----------------------------------------------------------------------------
# Common variables
# shifting channels based on rules:
# CH_SHIFT[rule_name] = {src_1_based_ch:new_1_based_ch}
CH_SHIFT = {}
CH_SHIFT[None] = None
# for 1-to-1 cards
CH_SHIFT['1to1'] = {}
for ch1 in xrange(1,... |
8,256 | c972f732553f27261d2a4a03e6e353f2e1b5f5d3 | import numpy as np
from .basic import scRefData, featureSelection
from .utils import find_variable_genes, dropout_linear_model
from .process import find_de_tt, find_de_anova
"""
after normalization
befor cluster or nn_indexing
"""
class highlyVarSelecter(featureSelection):
"""
select highly varable genes;
... |
8,257 | 61019a5439a6f0c1aee51db9b048a26fb9b5bf5d | # The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word... |
8,258 | cccf6ec50ae00d8e00a1a53ea06fa8b6d061b72e | from django.core.management.base import BaseCommand, CommandError
from tasks.redisqueue import RedisQueue
from django.conf import settings
class Command(BaseCommand):
def handle(self, *args, **options):
rqueue = RedisQueue(settings.REDIS_URL)
rqueue.worker()
|
8,259 | 89ed30411c624e3d930db0bc0b5b716a10908727 | """inactivate fb posts
Revision ID: f37637c1bcf8
Revises: 43c7ecf8ed02
Create Date: 2017-06-22 12:01:59.623040
"""
from alembic import op
from pd.facebook.models import MediaType
# revision identifiers, used by Alembic.
revision = 'f37637c1bcf8'
down_revision = '43c7ecf8ed02'
branch_labels = None
depends_on = None
... |
8,260 | cc33d0cf1b922a6b48fb83be07acb35a62372f2e | from .interface import AudioInterface
from .config import AudioConfig
from .buffer import CustomBuffer
|
8,261 | 909ea7b9335a858662f83abc71b4d58578bd0850 | """Settings module for test app."""
ENV = "development"
TESTING = True
SQLALCHEMY_DATABASE_URI = "sqlite://"
SECRET_KEY = "not-so-secret-in-tests"
DEBUG_TB_ENABLED = False
SQLALCHEMY_TRACK_MODIFICATIONS = False
APP_ENV = "testing"
JWT_SECRET_KEY = (
"-----BEGIN RSA PRIVATE KEY-----\n"
"MIICWwIBAAKBgQDdlatRjR... |
8,262 | 75d2dcbb0c131930602e3c1f2cf30c0e4c5e3c42 | import unittest
from display import Display
class TestDisplay(unittest.TestCase):
def setUp(self):
self.display = Display(None)
def test_set_pixels(self):
self.display.clear_buffer()
self.display.set_pixel(0, 1, 1)
self.assertEqual(self.display.get_pixel(0, 1), 1, "pixel was n... |
8,263 | 7dd4dc60b23c72ba450025bececb0e6d89df69c3 | from asteroidhunter import __version__
import unittest, requests, json, os, pytest
from dotenv import load_dotenv
load_dotenv()
from asteroidhunter.asteroid_closest_approach import asteroid_closest_approach
def test_version():
assert __version__ == '0.1.0'
@pytest.mark.vcr()
def test_asteroid_closest_approach():
... |
8,264 | 0d322bdaf1bfed2b76172cc4dfb1b9af52bdc641 | import urlparse
def parse_url(url):
"""
Parse a url into a ParseResult() object then evolve that ParseResult()
instance into an EasyUrl() object, finally return the EasyUrl() instance.
"""
url = urlparse.urlparse(url)
#print url.__class__
return EasyUrl.EvolveParseResult(url)
class ... |
8,265 | 8c652f30cd256912512b6b91d1682af7da0ff915 | import requests
seesion=requests.Session()
header={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3387.400 QQBrowser/9.6.11984.400'}
cookie={'Cookie':'_ga=GA1.2.1866009938.1500885157; xmuuid=XMGUEST-B6484440-71B8-11E7-AF2E-EFCFEDA... |
8,266 | 78e008b4a51cdbbb81dead7bc5945ee98ccad862 | def test(x):
print x
|
8,267 | cde2454c68a0d6a0c86b7d647e41a86d3aa97a0d | """
r - reading fike
w - writing to file
a - append to file / add to the end of the file - always at the end
r+ - read and write to file (writing based on python cursor position) -> by default at the beginning of file -> won't insert and shift things over,
will overwrite the contents. -> r+ can only be used with alread... |
8,268 | 4f36c7e98c54d38aaef9f2ebdafd0c34a157fcd7 | class Area :
def circle(self):
rad = int(input("Enter the radius:"))
area = (22/7)*(rad**2)
print("Area is :" , area , "cm square")
def square(self):
side = int(input("Enter the length of a side:"))
area = side**2
print("Area is :" , area , "cm s... |
8,269 | cffc64970cb82072e5fb949f62e9778942b2be96 | #!ipython3
pi_f = 0.1415926
pi = []
for i in range(10):
pi.append(str(pi_f * i*16)[0])
print(pi)
def convertBase(digits, baseA, baseB, precisionB):
return output
#0.56 b8 to b10
#(1/base) ^ (i+1) *x
to10('56')
test = list(str(56))
test
27 9 3
33
0.3212 * 3
4*1.5
0.3212* 4/6
3*3**-1
2*3**-2
1*3**... |
8,270 | d95cbca8e892f18f099b370e139176770ce0c1b7 | # 文字列(結合)
str1 = "py"
str2 = "thon"
print(str1+str2)
|
8,271 | 264b48c2b9ce4ec948ca5ba548e708848760f3dc | # Merge sort is used to sort the elements
def merge_sort(arr):
if len(arr) > 1:
# Recursion is used to continuously split the array in half.
mid = len(arr) // 2
# Using Auxiliary storage here
left = arr[:mid]
right = arr[mid:]
# Traverse the left side of the array
... |
8,272 | e5a4ae2ec0fab1ca8cdce229c69725ece2dcc476 | import numpy as np
import ipywidgets as widgets
from ipywidgets import interact, interactive, fixed, Layout, VBox, HBox
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.tri as tri
import matplotlib.colors as colors
from matplotlib.colors import LinearSegmentedColormap
import scipy.stats as sps... |
8,273 | eb827998f1ba75ffb95751ddb2b31d4d0e54358b | import numpy as np
import csv
class PriceTracker:
def __init__(self):
pass
def getValue(self, i):
pass
class CsvTracker:
def __init__(self, csv_file):
self.current_row = 61
self.csv_file_content = []
self.csv_file = csv.reader(csv_file, delimiter =',')
fo... |
8,274 | 12fdeae0ae1618139b20176846e7df5b82f7aa01 | from pyspark import SparkContext, RDD
from pyspark.sql import SparkSession, DataFrame
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
import string
from kafka import KafkaProducer
import time
import pyspark
sc = SparkContext(master='local[4]')
ssc = StreamingContext(sc, b... |
8,275 | 414fb437783fcfb55f542f072aaf3a8bb02b441e | import ipaddress
import subprocess
from subprocess import Popen, PIPE
import time
ip_net = ipaddress.ip_network('192.168.0.100/30')
for i in ip_net.hosts():
# print(i)
host_add = str(i)
toping = subprocess.Popen(['ping', '-n', '3',host_add],stdout=PIPE)
output = toping.communicate()[0]
... |
8,276 | 010a132645883915eff605ae15696a1fac42d570 | import math
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def value(energy, noise, x, gen):
logp_x = energy(x)
logq_x = noise.log_prob(x).unsqueeze(1)
logp_gen = energy(gen)
logq_ge... |
8,277 | 2804d49fc9f0e40859de1e8eb4f04a849639b1d4 | __author__ = 'Freek'
__build__ = 'versie 1.0'
from iNStagram.file_io.fileio import lees_stationgegevens
from iNStagram.api_requests.app_requests import request_instagram
from tkinter import *
startscherm = Tk()
startscherm.title('Foto of video in de buurt!')
startscherm.minsize(width=790, height=600, )
startscherm.c... |
8,278 | fd1b871c5cf79874acf8d5c4f1f73f7a381e23f7 | # This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.
import datetime
import scrapy
from ScrapyProject.items import ScrapyItem
class ThalesSpider(scrapy.Spider):
#item_id = ScrapyItem()
name = 'thales'
allo... |
8,279 | 0edc0c2f86bda0122d4b231eed700d7a5b08ec1e | from proxmin import nmf
from proxmin.utils import Traceback
from proxmin import operators as po
from scipy.optimize import linear_sum_assignment
import numpy as np
import matplotlib.pyplot as plt
import time
from functools import partial
# initialize and run NMF
import logging
logging.basicConfig()
logger ... |
8,280 | faf2f5da92cf45cfedda91955688b3ca1c7c0db9 | # -------------------------------
# --------- Set Methods ---------
# -------------------------------
# difference() return the values in the first set that not in the second set
set1 ={1, 2, 3, 4, 5, 6, 7, 8 , 9}
set2 = {1, 2, 3, 4, 5, 6, "A", "B"}
print(set1)
print(set2)
print(set1.difference(set2))
print(set1-set2... |
8,281 | 4af573fa17f86ee067b870dce1f6ee482d1b14ff | """
Декоратор parser_stop - парсер результата вывода комманды docker stop.
"""
from functools import wraps
def parser_stop(func):
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
stdout = result['stdout']
"""
stdout: строки разделены \n
"""
... |
8,282 | 51358ac7d4fc093f8291cfd9f098e3ac3db86cce | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os, uuid, re, sys
from decimal import Decimal
from datetime import date, time, datetime
from functools import lru_cache
from typing import Iterator
import pyodbc, pytest
# WARNING: Wow Microsoft always manages to do the stupidest thing possible always trying to be
# ... |
8,283 | ff9376ab4d6a88849167fb6e180fd9c4f9ab4dad | # -*- coding: utf-8 -*-
import os
import sys
import base64
import cdutil
import json
import os
from array import array
from uuid import uuid4
import cdms2
import numpy as np
import matplotlib as mpl
mpl.rcParams['mathtext.default'] = 'regular'
mpl.use('qt4agg')
import matplotlib.pyplot as plt
from mpl_toolkits.ba... |
8,284 | 6962bf99e3ecae473af54ded33fde09527cb82c0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 18:40:07 2021
@author: tomachache
"""
import numpy as np
from qiskit import *
# Various state preparation
def state_preparation(m, name, p):
# m : nb of qubits
# name : name of the state we want
# p : proba associated with nois... |
8,285 | f502290cc8ffa9571454a214497aff1d1c5e1c9f | var blackList = []string{
// global
"document", "window", "top", "parent", "global", "this",
//func
"console", "alert", "log", "promise", "fetch", "eval", "import",
//char
"<", ">", "`", "\\*", "&", "#", "%", "\\\\",
//key
"if", "set", "get", "with", "yield", "async", "wait", "func", "for", "error", "string",
... |
8,286 | 3ebd455056f168f8f69b9005c643c519e5d0b436 | import os
import glob
import pandas as pd
classes = os.listdir(os.getcwd())
for classf in classes:
#if os.path.isfile(classf) or classf == 'LAST':
#continue
PWD = os.getcwd() + "/" + classf + "/"
currentdname = os.path.basename(os.getcwd())
csvfiles=glob.glob(PWD + "/*.csv")
df = pd.DataFrame(columns=['im... |
8,287 | eab2cdd92d3be5760f13e747b05ca902eaf9aca8 | import sys
import os
arcpy_path = [r'D:\software\ArcGIS\python 27\ArcGIS10.2\Lib\site-packages',
r'D:\software\ArcGIS\Desktop 10.2\Desktop10.2\arcpy',
r'D:\software\ArcGIS\Desktop 10.2\Desktop10.2\bin',
r'D:\software\ArcGIS\Desktop 10.2\Desktop10.2\ArcToolbox\Scripts']
sys.pa... |
8,288 | cce40ff190f7790ac4eca7d6cb3c032955bb4849 | """
Copyright 2020 Google LLC
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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
di... |
8,289 | 8f5b7711d913c7375d6816dd94731f1ce5ca1a62 | from template.db import Database
from template.query import Query
import os
'''
READ ME!!
Before using this demo, be sure that the Tail_Const is set to a value high enough
to guaranteed that all updates are contained within the same block.
config.py -> TAIL_CONST = 4
This program is mean... |
8,290 | 781cb59fb9b6d22547fd4acf895457868342e125 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-17 14:47
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('votes', '0003_choice_votes'),
]
operations = [
migrations.CreateModel(
... |
8,291 | 97d84f99264afa5e7df4b5d22cf4c49b2d14ff7a | def word_count(s):
# Your code here
cache = {}
ignore = '":;,.-+=/\\|[]{}()*^&'
lower = s.lower()
for i in lower:
if i in ignore:
lower = lower.replace(i, '')
words = lower.split()
for j in words:
if j not in cache:
cache[j] = 1
else:
... |
8,292 | 02f196623907703255bf149db0435104d086da97 | import numpy as np
import cv2
import time
from itertools import chain, compress
from collections import defaultdict, namedtuple
class FeatureMetaData(object):
"""
Contain necessary information of a feature for easy access.
"""
def __init__(self):
self.id = None # int
... |
8,293 | 19b55b2de3d2ed16275cef572e3518fbb2457f84 | from django import forms
class photoForm(forms.Form):
iso = forms.ChoiceField(label='ISO', choices=[("100", 100),
("200", 200),
("300", 300),
("400", 400),
... |
8,294 | 1d1576825f80c3b65ce1b7f8d1daccbbf8543d7d | # -*- coding: utf-8 -*-
import numpy as np
import pickle
import os
import feature_extraction
#import topic
file1 = open('vecdict_all.p', 'r')
file2 = open('classif_all.p','r')
vec = pickle.load(file1)
classifier = pickle.load(file2)
file1.close()
file2.close()
#sentence = "I never miss the lecture of Dan Moldovan... |
8,295 | e8b0e6e5e68933703e2ac8c9b2b62d68c0c2f53d | # coding=gbk
from numpy import *
import fp_growth
'''
#创建树的一个单节点
rootNode=fp_growth.treeNode('pyramid',9,None)
#为其增加一个子节点
rootNode.children['eye']=fp_growth.treeNode('eye',13,None)
rootNode.disp()
#导入事务数据库实例
simpData=fp_growth.loadSimpData()
#print("simpData:")
#print(simpData)
#对数据进行格式化处理
initSet=fp_growth.cre... |
8,296 | 8fb559810fbf79f0849ed98e51d3f2ad1ccc4b8b | from typing import List
h = 5
w = 4
horizontalCuts = [3]
verticalCuts = [3]
class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts.sort()
verticalCuts.sort()
horizontalCuts.append(h)
verticalCuts.append(w)
... |
8,297 | 7b920545a0241b30b66ff99f330dbb361f747f13 | card = int(input())
last4 = card % 10000
print(last4) |
8,298 | faafc7cfd900d3f6fd6df30af5580f71eecfb279 | import torch
import torch_scatter
import torchgraphs as tg
import textwrap
from . import autograd_tricks as lrp
def patch():
torch.add = lrp.add
torch.cat = lrp.cat
torch.index_select = lrp.index_select
tg.utils.repeat_tensor = lrp.repeat_tensor
torch_scatter.scatter_add = lrp.scatter_add
... |
8,299 | 086aefaad7a4b743e5a05b3a44db971dbdbf16b6 | import tensorflow as tf
from sklearn.cluster import KMeans
import tensorflow.keras as keras
from copy import deepcopy
import numpy as np
import h5py
from collections import defaultdict, namedtuple
from heapq import heappush, heappop, heapify
import struct
tf.enable_eager_execution()
mnist = tf.keras.datasets.mnist
(x... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.