index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
990,300 | 414ff8f6129b70ad98a46db570fd287457701ce1 | import os
import numpy as np
from matplotlib import pyplot as plt
import sys
sys.path.append("../utilities")
import constants
import utils
import data
def plot_histograms(run_dir, metadata_sig, metadata_bg):
#trim to even size
if metadata_bg.shape[0] > metadata_sig.shape[0]:
metadata_bg = metadata_bg[:metada... |
990,301 | 7c28662af031537fc9c940dfe88c2a7f352d1eaa | """Basic loading & dumping functions."""
from pathlib import Path
from typing import Sequence
import tablib
from peewee import Model
from songbook import models
def _dump_table(table: Model, directory: Path, format_: str):
"""Dump a single table."""
try:
table.select().tuples()
table.fields(... |
990,302 | 0d6a09d7f4145dad5f64ad85d4696b4b8f03fa86 | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
class DannyGRnR():
def __init__(self, ifilepath=None, idata=None, iUSL=0, iLSL=0, ivaluelist = None, ifigname='My CPK'):
self.iUSL = iUSL
self.iLSL = iLSL
self.data = idata
self.ifigname = ifigname
... |
990,303 | e4fdc8b43e224a182d309628837f33ad1c7241f3 | import serial
import struct
ser = serial.Serial(port='/dev/ttyS0',baudrate=115200)
def serialLoop():
seri = [0]*3
while True:
line = ser.read()
line = struct.unpack('B',line)
if line[0] > 127:
seri[0] = line[0]
line = ser.read()
... |
990,304 | e4e42a7944c168a915ac4ee0a91ccdc12ef874c3 | a = 3
b = 2
resultado = (a == b)
print(resultado)
resultado = (a != b)
print(resultado)
resultado = (a > b)
print(resultado)
resultado = (a >= b)
print(resultado)
resultado = (a <= b)
print(resultado)
resultado = (a < b)
print(resultado) |
990,305 | 6f4bf8d0a1eca8264b3aae3dcd89e0ab0574f385 | def evaluate_policy(env, policy, trials = 1000):
total_reward = 0
for _ in range(trials):
env.reset()
done = False
observation, reward, done, info = env.step(policy[0])
total_reward += reward
while not done:
observation, reward, done, info = env.step(policy[ob... |
990,306 | f569e69ca5d8c8a18e175bc40b40a8ee7cbd81c2 | class DatosMensaje:
def __init__(self):
self.Nombre = ""
self.Mensaje = "" |
990,307 | 2bc074b388b899edc666098262184ba22e40ce5d | from PIL import Image, ImageDraw
from BreastCancerDiagnosis.Model import Net as BreastCancerModel
import numpy as np
from torch import load
from torchvision import transforms
from SkinCancer.Model import Net as SkinCancerModel
x=Image.open('samples/skin_cancer_benign.jpg').convert('RGB').resize([300,300])
x.show()
img... |
990,308 | f75710d49ff478b675faf720ff3d31f950d951f8 | # setup.py
import sys, pathlib, re, json
from setuptools import setup, find_packages
# --- Get the text of README.md
HERE = pathlib.Path(__file__).parent
README = (HERE / "README.md").read_text()
# --- Get the version number
reVersion = re.compile(r'^__version__\s*=\s*\"(.*)\"')
version = ''
with open('./parserUtils... |
990,309 | d697aa17dc89830fa6f8e973991b1ff00277c837 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (
print_function,
division,
absolute_import)
from six.moves import xrange
# =============================================================================
# Imports
# =======================================================================... |
990,310 | 02920141e923403a5a605c6faa572f6561066e59 | import asyncpg
from settings import settings
class Pool:
async def open_pool(self):
self.pool = await asyncpg.create_pool(dsn=settings.PGSTRING)
async def close_pool(self):
await self.pool.close()
def get_pool(self):
return self.pool
db = Pool()
|
990,311 | e68e7b2479d2625d6256614d519e6c852bc34eb6 | from .models import Produto
from django.forms import ModelForm
from django import forms
class ProdutoFrom(ModelForm):
class Meta:
model = Produto
fields = ['descricao', 'preco']
def send_email(self):
pass
|
990,312 | c796cb5535169e91ac860ff06d62ee1f40b94427 | # USAGE
# python build_dataset.py
# ========================
# ~/mxnet/bin/im2rec /raid/datasets/adience/lists/age_train.lst "" \
# /raid/datasets/adience/rec/age_train.rec resize=256 encoding='.jpg' quality=100
# ~/mxnet/bin/im2rec /raid/datasets/adience/lists/age_val.lst "" \
# /raid/datasets/adience/rec/age_val.re... |
990,313 | 87970e05ffc15fc93d41716f813d5d88ed37bb1e | import os
import platform
import subprocess
import sys
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
__version__ = '0.8.0'
__milecsa_api_version__ = '1.1.3'
darwin_flags = ['-mmacosx-version-min=10.12']
class ExtensionWithLibrariesFromSources(Extension):
"""Win is u... |
990,314 | 7b48983ee2f981ccc42afb5d4a2ec52fe8000dd7 | import numpy
import Family
def sinx_x(x):
y = numpy.array(1)
sin = numpy.sin(x)
y = numpy.divide(sin, x, where=x != 0) or 1
return y
def cosx_x(x):
y = numpy.array(1)
cos = numpy.cos(x)
y = numpy.divide(cos, x, where=x != 0) or 1
return y
def main():
father_name, father_age = i... |
990,315 | 0c109b6e0fc2e0460531af804070ea8b660524d9 | #coding=utf-8
import time
import cv2
#初始化 opencv 的 Cascade Classification,它的作用是产生一个检测器
faceCascade = cv2.CascadeClassifier("/usr/share/opencv/haarcascades/haarcascade_eye.xml")
image = cv2.imread("02.jpg")
#图像灰度化
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#调用
time1=time.time()
faces = faceCascade.detectMultiScale... |
990,316 | 3fcfb9bc1ce76fc51bcc556cf9de955558e57dd6 |
class NeuralNet(object):
"""Neural Network
A multilayer perceptron is a feedforward artificial neural network model
that has one layer or more of hidden units and nonlinear activations.
Intermediate layers usually have as activation function tanh or the
sigmoid function (defined here by a ``Hidden... |
990,317 | 73e6d4610f9045b4f1220fc56bd23ab00d2e1802 | import math
from datetime import datetime
import datetime
import time
import pandas as pd
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
from django.db import connection
from django.http import HttpResponse, JsonResponse
from djang... |
990,318 | 9610c1fcce2b3fab3b79e2a8d76bab7ac9e690e2 | import struct
from enum import Enum
from enum import IntEnum
from tls_parser.exceptions import NotEnoughData, UnknownTypeByte, UnknownTlsVersionByte
from tls_parser.tls_version import TlsVersionEnum
from typing import Tuple, Sequence
class TlsRecordTlsVersionBytes(Enum):
SSLV3 = b"\x03\x00"
TLSV1 = b"\x03\x01... |
990,319 | f5e5e045ca7b180236f23679a34a8ffc7d86d6da | import graphene
from graphene_django import DjangoObjectType
from todocore.models import Todo, Task , Comment, File
import json
from todocore.users.schema import UserType
class TodoType(DjangoObjectType):
class Meta:
model = Todo
class Query(object):
all_todos = graphene.List(TodoType)
def reso... |
990,320 | 0952efa709c583f2a1249aad3b6533ed90c4a362 | #!/usr/bin/env python
# -*-encoding:UTF-8-*-
import os
# os.path.abspath(__file__) will return the absolute path of .py file(full path)
# os.path.dirname(__file__) will return the file dir of .py
# basedir is the root dir:ICQBPMSSOJ
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# postgresql:d... |
990,321 | d3e09f7dd9a5411c6e750b463be406bec3b4c4d6 | import cmath
a = int(input())
b = int(input())
c = int(input())
d = (b**2)-(4*c*a)
root1 = (-b-cmath.sqrt(d))/(2*a)
root2 = (-b+cmath.sqrt(d))/(2*a)
print("the roots are {} and {}".format(root1,root2))
|
990,322 | f9b67f3566aa027474546f5bbbe1222ab78defc0 | import numpy as np
def slice2d_intrange(dists, trange):
"""
Retrieves the indices of all samples in the specified time range from a particle distribution list.
Input
------
dists: list of particle distributions
trange: array of float
Time range to find distributions in; m... |
990,323 | 3a8d4aa38835d8dff1ebb67620bd2d79547b7702 | #&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LIBRERIAS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&... |
990,324 | b57a87a3a5e47b37f10ebb2f8738739c2a3c2ba5 | #!/usr/bin/python
# airfoil slicer
# accepts coordinate CSVs from http://airfoiltools.com/plotter
# outputs gcode
from math import *
class GCodeGen:
def __init__(self):
self.extruderTemp = 190.
self.filamentDiameter = 1.75
self.extruderDiameter = 0.4
self.layerHeight = 0.3
... |
990,325 | abe85a8bfb46a7099320f9a6d1cc44f5057ea62b | import random
import numpy as np
import scipy.ndimage
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import platform
import odl
import pydicom as dc
from scipy.misc import imresize
import util as ut
# Objects of the data_pip type require to admit a method load_... |
990,326 | d2c3f4b2c8d8b3261ebb3c2ad76ab619add5a56a | """Convolutional implementation of N-Dimensional Neighborhood Thresholding.
Functions
---------
conv_ndnt
"""
import itertools
import functools
import numpy as np
import scipy.ndimage as ndi
def conv_ndnt(data, shape, threshold):
"""Compute the N-Dimensional neighborhood threshold of an image.
Parameters
... |
990,327 | a66f26f6d75bbcd7ffac3ad250df09fc8822c9bb | from django.urls import include, path, reverse
from . import views,views_latex
urlpatterns = [
path('', views.index, name='index'),
path('exams/',views.examlist,name='examlist'),
path('exams/<int:exam_id>/',views.examdetail,name="examdetail"),
path('exams/<int:exam_id>/add_question/<int:question_id>',v... |
990,328 | 8755eca31306c168c3e97f31bebc16d56c67bc4b | # Absolute local
from bgt import create_app
app = create_app()
|
990,329 | 6c04de5a47ef83261f2c400248c193139ef9fac5 | #!/usr/bin/python3
import urllib.request
import sys
import logging
import tempfile
import os
import re
import json
import argparse
import shutil
import stat
from zipfile import ZipFile
libindex = {
'win32': {
'x64': {
'generic': [
{
'name': 'clang',
... |
990,330 | 6c06f383c4093540d7820dba99ac523eb00128ad | # Enthusiastic_Python_Basic #P_05_2_4
st = [1, 2, 3, 4, 5]
st[0:5] = []
print(st) |
990,331 | b0d032aa2646964bd59e081fcea30bb01ec5a2d4 | import turtle
print("Happy Onam")
tim = turtle.Turtle()
tim.speed(5000)
def petal(length=200,x1=0,x2=0,x3=0):
tim.color(x1,x2,x3)
tim.begin_fill()
for i in range(9):
tim.forward(length)
tim.circle(length/4,208)
tim.forward(length)
tim.right(180)
tim.right(-17)
tim.end_fill()... |
990,332 | 77b5e6a3f74a8fdcd740ecd4cad6b7d1272769d3 | #!/usr/local/bin/env python3
from beautifulscraper import BeautifulScraper
scraper = BeautifulScraper()
body = scraper.go("https://github.com/adregner/beautifulscraper")
body.select(".repository-meta-content")[0].text
|
990,333 | e3a685f0f8b640e926ddea95434c0f36a911633b | data = [
1941
, 1887
, 1851
, 1874
, 1612
, 1960
, 1971
, 1983
, 1406
, 1966
, 1554
, 1892
, 1898
, 1926
, 1081
, 1992
, 1073
, 1603
, 177
, 1747
, 1063
, 1969
, 1659
, 1303
, 1759
, 1853
, 1107
, 1818
, ... |
990,334 | e34b4641b2bde0b8af9c6d5d15e5eacebba857a9 | from Sistema_Locadora.Connection_DataBase.Connection import Connection
from Sistema_Locadora.Operations_CRUD.Date_Hour_Now import DateHourNow
class DvdGame(Connection):
global date_hour
now = DateHourNow()
date_hour = now.get_date_hour_now()
def check_qtde_dvd_games_avaible(self, id_dvd_jogo):
... |
990,335 | a42fdf7cd6e4369e2e23dbf5260c4fc886b5aed8 | from create_project import *
|
990,336 | 2ac2421332e9fef0a94c1be742a83d2294b96c30 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: rtwik
"""
from setuptools import find_packages
from setuptools import setup
setup(
name='writing_level_classifier',
version='0.1.dev0',
packages=find_packages(),
install_requires=[
"Keras == 2.1.5",
"tensorflow == 1.6.0",
... |
990,337 | 8efece4478950f085da119598b82f1961e232dd0 | class CharClass:
""" Character Base Class """
def SetForce(self):
self.cForce['health'] = self.cStats['end'] * 3
self.cForce['mana'] = self.cStats['int'] * 4
self.cForce['dam'] = self.cStats['str'] * 2
def __init__(self, Name = "NONE", Race = "Human", Class = "Warrior", Stats = {'str': 1, 'int': 1, 'end': 1}... |
990,338 | 2b962fb3c0c33a5e21d4c5a53bf6118f494024a9 | # package definitions
BITBUCKET = [
# (python_package_name, bitbucket_owner_name/bitbucket_organization, bitbucket_repo_name)
# for example, consider an entry for https://bitbucket.org/atlassian/python-bitbucket
# ('pybitbucket', 'atlassian', 'python-bitbucket')
]
# --- local git repositories
# format :: ... |
990,339 | a62b8254569ce2cb96138020b6b50a2caf98b0b9 | from sqlalchemy import create_engine
e = create_engine("mysql+pymysql://vcchau:parksareawesome@parksareawesome.chr9q1gt6nxw.us-east-1.rds.amazonaws.com:3306/parksareawesomedb")
e.execute("""
drop table events;
""") |
990,340 | f9c6166557440e0ddbc304a46b29ac16cc2638f1 | import datetime
import math
import numpy as np
import pytest
from .country_report import CountryReport
from .formula import AtgFormula
def test_two_traces():
cumulative_active = np.array([0, 0, 1, 2, 5, 18, 45])
start_date = datetime.date(2020, 4, 17)
dates = [start_date + datetime.timedelta(days=d) for... |
990,341 | ee4f1f3410c48e8b5dbce55805743be0c6b9ee0d | ''' Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com a média atingida:
- Média abaixo de 5.0: REPROVADO
- Média entre 5.0 e 6.9: RECUPERAÇÃO
- Média 7.0 ou superior: APROVADO'''
n1 = float(input('Digite a Primeira Nota: '))
n2 = float(input('Digite... |
990,342 | 55bca2c24303401024774d64bbebd1b6b239d6eb | import datetime
import operator
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict
import db_mac
from _collections import OrderedDict
# precision
airlines_score = dict()
sql1 = "select aircraft, count(*) from od2 where bound like 'in' and timestamp::time > '07:59:00'::... |
990,343 | 9d673ca06275bfafc40637d7f9308d424b5e5245 | mydict={
"name":"sakssham mudgal",
"class": "btech",
"roll no":[1900330100188,2019]
}
#can use single quotes
print(mydict['name'])
print(mydict['class'])
print(mydict['roll no'])
#can use double quotes
print(mydict["name"])
print(mydict["class"])
print(mydict["roll no"])
#nested dictionary
myfirstdict={
... |
990,344 | ef6cb3b8757ec2f0fc31710a276a20b8c9325f75 | ba=input()
if ba.isalpha():
za=ba.lower()
if za=="a" or za=="e" or za=="i" or za=="o" or za=="u":
print("Vowel")
else:
print("Consonant")
else:
print("invalid")
|
990,345 | c062c6bbe1fdd3f3c03470f36a416a36a17fdb83 | from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from invitation.views import request_invite, approve_invite
urlpatterns = patterns('',
url(r'^complete/$', TemplateView.as_view(template_name='invitation/invitation_complete.html'), name='invitation_complete'),
url(r'^invi... |
990,346 | f4e821a128cd680f6dc33526024e9888c42c2fd7 | from simulations.recreate_collisions import create_cars_from_collision_json
from json import JSONDecoder
import os
log_directory = os.path.dirname(os.path.abspath(__file__)) + "/../logs/"
reading_file = open(log_directory + "collisions1.log")
file_string = "["
for line in reading_file:
file_string += line
file_str... |
990,347 | c7a365d6aa93e1393b24fc05eb2527ddbbf64784 | # 1 创建学生表:有学生 id,姓名,密码,年龄
create table student(
id int primary key auto_increment,
name varchar(50) not null,
password varchar(25) default '123',
age varchar(10)
);
# 2 创建学校表:有学校id,学校名称,地址
create table school(
id int primary key auto_increment,
name varchar(50) not null,
address varchar(... |
990,348 | 0c3d7c323283a1d761e3912ea940d72d5dbc7e4c | import time
import sys
class Problem():
def __init__(self):
self.orientation = (0, 1) # (0,1) = haut (1,0) = droite (-1,0) = gauche (0,-1) = bas
self.position = (50, 50) # position actuelle de la fourmi sur la grille
self.compteur_de_noirs = 0 # compte le nombres de cases noires sur l... |
990,349 | 8535a43af5567ad7a8fd991b90b5f491149aa6be | # Queue is a FIFO structure.
from collections import deque
class Queue(object):
def __init__(self):
self.items = deque()
@classmethod
def new(cls):
queue = cls()
return queue
def insert(self, data):
self.items.appendleft(data)
def pop(self):
return self.... |
990,350 | dabb3a9dbf31cbda5586b4c0074211fc80cc6c62 | from messages import *
from kickstarter import *
from twitter import *
from rss import *
from valenbisi import *
|
990,351 | a77b0d720d9d1a4e1ffc360ed167fbd995863d36 | #!/usr/bin/env python
__import__('sys').path.append(__import__('os').path.join(__import__('os').path.dirname(__file__), '..'))
__import__('testfwk').setup(__file__)
# - prolog marker
import os, logging
from testfwk import create_config, run_test, str_dict_testsuite, testfwk_set_path, try_catch
from grid_control.backend... |
990,352 | da9191e54b1177c4138170da01204691101bfc09 | import httplib, urllib, base64, json
import time
headers = {
# Request headers.
'Content-Type': 'application/json',
# NOTE: Replace the "Ocp-Apim-Subscription-Key" value with a valid subscription key.
'Ocp-Apim-Subscription-Key': '69766cdb74e748cd9266eb53fae6316f',
}
# Replace 'examplegroupid' with ... |
990,353 | 17843ec288ba1e31db06f48e2ab9aa9a5c748083 | import numpy as np, cv2
# 회선 수행 함수
def filter(image, mask):
rows, cols = image.shape[:2]
dst = np.zeros((rows, cols), np.float32) # 회선 결과 저장 행렬
xcenter, ycenter = mask.shape[1] // 2, mask.shape[0] // 2 # 마스크 중심 좌표
for i in range(ycenter, rows - ycenter): # 입력 행렬 반복 순... |
990,354 | e0dabc6ad9b501311df22bf6de048ce5e20adda5 | from .conf import config
app_name = "microsoft_auth"
urlpatterns = []
if config.MICROSOFT_AUTH_LOGIN_ENABLED: # pragma: no branch
from django.conf.urls import url
from . import views
urlpatterns = [
url(
r"^auth-callback/$",
views.AuthenticateCallbackView.as_view(),
... |
990,355 | 3b1f2ce98baf9d82a7d341b715aa38fc8f84aefa |
#-----------------------------
def test () :
return 'Zoe'
print (test()) # Zoe
#-----------------------------
a = 1
b = 2
def test ( a , b ) :
c = a + b
return c
print (test(a , b)) # 3
#-----------------------------
a = 'apple'
b = 'banana'
def test ( a , b ) :
return a
print (test(a , b)) #... |
990,356 | 126caab087097aebe661f9673bd02fd4449d7222 | """Quick Scan a folder or a bucket"""
# _______ ___ ___ ___ _______ ___ ___ _______ _______ _______ ______ _______ _______ ___
# | _ | Y | | _ | Y ) | _ | _ | _ | _ \ | _ | _ | |
# |. | |. | |. |. 1___|. 1 / | 1___|. 1___|. 1 |. | | |. 1 ... |
990,357 | 94a95ddd23a5f3e10f55b7c5bdbf18bd22155ad4 | #!/usr/bin/python
#import time
import os, sys, fnmatch
import shutil
from subprocess import Popen, PIPE
def invoke_klee():
# invoke bytecode from "BC" folder
bcfiles = []
for path, dir, files in os.walk(os.path.abspath(os.getcwd()+"/bcfiles")):
for filename in fnmatch.filter(files, "*.bc"):
bcfiles.append(os.p... |
990,358 | d682f2d8c6553a7607a6b64f572aeab869a24add | import command_system
import vkapi
import db
import keyboards as kb
import settings
def next(vk_id, body):
if vk_id not in settings.admin_ids:
return None, None
if not body.startswith('/пригласить'):
return None, None
year = body.split()[1]
msg = 'Добрый вечер!\n\n'
msg += 'В пр... |
990,359 | cf6ec39c1b090382ebdd6b01472c36e535108dff | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 19 20:00:25 2019
@author: Mohammad Shahin
"""
def interlaced(st1,st2):
print(len(st2))
small=''
if len(st1)>len(st2):
x=st1[len(st2):]
small=st2[:]
elif len(st2)>len(st1):
x=st2[len(st1):]
small=st1[:]
res=''
for i i... |
990,360 | 2c3973431f55f27f19154ec3addbfb0e5104d66e | from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
import requests
import re
from bs4 import BeautifulSoup
import pandas as pd
import xlrd
import openpyxl
pd.set_option('display.max_columns', None)
import numpy as np
from datetime import date,... |
990,361 | 9821623c705844f9159abd7122d77485faa34041 | from flask import render_template, flash, redirect, url_for
from app import app
from app.forms import ContactMeForm
from flask_pymongo import PyMongo
mongo = PyMongo(app)
@app.route('/')
@app.route('/index')
def index():
user = {'username': 'Imran'}
posts = [
{
'author': {'username': 'John... |
990,362 | 103dcda6f719691d657ec0986095a5dd54aa5038 | import math
import time
colors = ['\033[95m', '\033[94m', '\033[92m', '\033[91m', '\033[99m']
for cycleCount in range(1,4):
frequencies = [10, 25, 30, 98]
times = [.001, .01, .0001, .005]
for timeOffset in times:
for frequency in frequencies:
for color in colors:
for cycle in range(0, int(math.pi*2*freq... |
990,363 | 3874189b9662d11b43d49eb1bae5a1379a5d47ef | from pycqed.measurement.calibration.automatic_calibration_routines.base import\
update_nested_dictionary
from .base_step import Step, IntermediateStep
from pycqed.measurement.calibration import single_qubit_gates as qbcal
from pycqed.measurement.quantum_experiment import QuantumExperiment
from pycqed.utilities.gen... |
990,364 | 3e42b7d59de2a8da2fed873088a477e0dfbdfdc0 | # coding: utf-8
"""
Magento Community
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import... |
990,365 | 3f86870ac881235a34962bfeba12779634df4474 | import pandas as pd
import numpy as np
from pandas import DataFrame ,Series
data_train = pd.read_csv("train.csv")
import matplotlib.pyplot as plt
fig = plt.figure()
#图案颜色
fig.set(alpha = 0.2)
# 获救
plt.subplot2grid((2,3),(0,0))
data_train.Survived.value_counts().plot(kind = 'bar')
plt.title('Surivred')
plt.ylabel('am... |
990,366 | 028430b4b2946b414336ed6558b62d3b06c1de48 | from libs.naver_shopping.crawler import crawl
from libs.naver_shopping.parser import parse
import json
pageString = crawl('')
products = parse(pageString)
print(len(products))
#json파일로 내보내기
##file = open("./products.json", "w+")
##file.write(json.dumps(products)) |
990,367 | 726d0c257249f2550cabb097464f41a592ab328b | # -*- coding: utf-8 -*-
# @Author : zhang35
# @Time : 2020/10/15 14:25
# @Function:
from database.postsqldb.db import db
from datetime import datetime
from geoalchemy2.types import Geometry
from flask_restful import fields
from geoalchemy2.elements import WKTElement
from statsmodels.tsa.statespace.varmax import VAR... |
990,368 | df12d2262770ec945abc4ceacd1addfabe00e5cd | #Reversing Strings
list1 = ["a","b","c","d"]
print (list1[::-1])
#Reversing Numbers
list2 = [1,3,6,4,2]
print (list2[::-1])
|
990,369 | 338c0899d16b062c3e66edae4031ecb44b4abc8d | from django.db import models
from django.contrib.auth.models import User
class Roles(object):
ADMIN = 0x01
CLIENT = 0x02
CHOICES = {
ADMIN: 'Admin',
CLIENT: 'Client'}
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
occupation = models.CharField(max_len... |
990,370 | 53fc4b03d09762e13cb4b7fc06108b21eabe7edb | #!/usr/bin/python
# Birthday wish program
# Demonstrates keyword arguments and default parameter values
# written for python2
# positional parameters
def birthday1(name, age):
print "Happy birthday,", name, "!", " I hear you're", age, "today.\n"
# parameters with default values
def birthday2(name = "Jackson", age ... |
990,371 | ce726fc3fdd7e3119216cef0358b1f8238768406 | __author__ = '368140'
from pymongo import MongoClient
import logging
import logging.config
import json
import os
import sys
logging.info('Reading config file')
## Initiating logging
default_logging_path = 'logging.json'
default_level = logging.INFO
env_key = 'LOG_CFG' # This environment variable can be set to load ... |
990,372 | ccf4d493740c1f1a0e10d7d732441b8b7c52e9ff | import FWCore.ParameterSet.Config as cms
import copy
import sys
sys.setrecursionlimit(10000)
process = cms.Process('runAHtoElecTau')
# import of standard configurations for RECOnstruction
# of electrons, muons and tau-jets with non-standard isolation cones
process.load('Configuration/StandardSequences/Services_cff')
... |
990,373 | cf397f4eda58325ccd6a4d875510fccf751c88f8 | from medium import Client
import webbrowser
import sys
import json
import requests
from fake_useragent import UserAgent
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from settings import *
callback_url = "https://lucys-anime-server.herokuapp.com"
ua =... |
990,374 | 5a82b3f8af0f23d356db3142a02753c1ff90542b | """
.. module: historical.s3.poller
:platform: Unix
:copyright: (c) 2017 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. author:: Mike Grima <mgrima@netflix.com>
"""
import os
import uuid
import logging
import boto3
from botocore.exceptions import ClientError
from ... |
990,375 | 28411c43ca332b061a8422a832fa7e92c159d849 | import numpy as np
import matplotlib.pyplot as plt
top_n = 13
num_terms = 100000
bins = [i for i in range(1, top_n+2)]
fig, ax1 = plt.subplots(figsize=(11, 8.5))
scaled_rps = [ [val/1000.0 for val in row] for row in rps]
ax1.boxplot(scaled_rps, positions = [i+0.5 for i in range(1,14)])
ax1.axis([1,15,0,250])
ax1.... |
990,376 | 9f40508f3c3671da7a79dfc1ce89b69f0dfa9ce6 | from random import randint
class BinarySearch():
def __init__(self):
self.tree = [None]
def add_element(self, element):
current_index = 0
while True:
if self.tree[current_index] == None:
self.tree[current_index] = element
while len(self.tree) < 2 * current_index + 3:
self.tree.append(None)
... |
990,377 | 480201c20039b4415cfe75da92fcc914db705a68 | import os
import chi
import numpy as np
import pints
def define_data_generating_model():
# Define mechanistic model
directory = os.path.dirname(os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
mechanistic_model = chi.SBMLModel(
directory + '/models/dixit_grow... |
990,378 | adf532fff8015876498bd6b992f46847fe0f6604 | # -*- coding: utf-8 -*-
from Hero_list import Timo, Jinx
class HeroFatory:
def create_hero(self, name):
if name == "timo":
return Timo()
elif name == "jinx":
return Jinx()
else:
raise Exception("不在英雄池内")
if __name__ == "__main__":
hero = HeroFator... |
990,379 | 34e738449eddd1a80bf07de7aeed9155ff35b104 | #!/usr/bin/env python
#
# NEED POSIX (i.e. *Cygwin* on Windows).
"""
Script to bump, commit and tag new versions.
USAGE:
bumpver
bumpver [-n] [-f] [-c] [-a] [-t <message>] <new-ver>
Without <new-ver> prints version extracted from current file.
Don't add a 'v' prefix!
OPTIONS:
-a, --amend Amend current c... |
990,380 | 8e8db60c156aa43294dc87c7c6348dfa4cecc6c8 |
# merge existing .pkl files into a single pkl file.
import pandas as pd
import numpy as np
import numpy as np
import collections
import matplotlib
# matplotlib.use('Qt4Agg')
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
from matplotlib import rc
# import pandas as pd
from random impor... |
990,381 | fce4024640c48290cb22fadf6e124d5346c8916b | """ loader.py
"""
import os
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torchvision.datasets import ImageFolder
def get_loader(config):
root = os.path.join(os.path.abspath(os.curdir), config.dataset)
print('[*] Load data from {0}.'.format(root))
... |
990,382 | 2dddd89352741022111793a41fe395439c1e7e81 | """pyglet_helper.ring contains an object for drawing a ring"""
try:
import pyglet.gl as gl
except Exception as error_msg:
gl = None
from pyglet_helper.objects import Axial
from pyglet_helper.util import Rgb, Tmatrix, Vector
from math import pi, sin, cos, sqrt
class Ring(Axial):
"""
A Ring object
"... |
990,383 | e7137d0669089683c1ea3c5813ee6b12b027d818 | #coding: utf-8
import os
import logging
import configparser
from seafevents.app.config import appconfig
MAX_LDAP_NUM = 10
class LdapConfig(object):
def __init__(self):
self.host = None
self.base_dn = None
self.user_dn = None
self.passwd = None
self.login_attr = None
... |
990,384 | fb70a2fa01d9ece0af30aedfe55cdfc3d6658fb9 | import os
from .utils import jsonfile2dict
class COCO2YOLO:
def __init__(self, annotations_dict, output):
self.labels = annotations_dict
self.coco_id_name_map = self._categories()
self.coco_name_list = list(self.coco_id_name_map.values())
self.output = output
def _categories(s... |
990,385 | 77db980ce887df0337024c79b1447b013272879a | import numpy as np
import matplotlib.pyplot as plt
# Define the number of samples
m=100
#Start to generate random feature X1
X1 = 6 * np.random.rand(m, 1) - 3
# Start to generate random feature X2
X2 = 3 * np.random.rand(m, 1) - 3
# Add X1,X2 to X0 which is the intercept feature
X = np.c_[np.ones((100,1)),X1,X2]
# Ge... |
990,386 | df3b83159d6013982a42be49b4b85b9c4a4cb774 | from django.urls import path
from users import views
urlpatterns = [
path(
route='signup/',
view=views.UsersSignUpView.as_view(),
name='signup'
),
path(
route='login/',
view=views.UsersLoginView.as_view(),
name='login'
)
]
|
990,387 | 92f4ea72568629da7cb27f7d1d44fdec6e0973fb | # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-06-19 12:33
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('my_app', '0001_initial'),
]
operations = [
... |
990,388 | 74988990f04a8e25bd51e2dcb8448a670bd19e9c | from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
def base(request):
return render(request, 'index.html') |
990,389 | 03471d933ac20a2b70e2d0f29e0fd8810735aa91 | string_to_search = input().lower()
list_of_words = ['sand', 'water', 'fish', 'sun']
word_count = 0
for word in list_of_words:
if word in string_to_search:
word_count += string_to_search.count(word)
print(word_count)
|
990,390 | 9b316ea4e84871d69ec8c9c4b31585cfd40012c1 | import pymongo
import json
from datetime import datetime
# 1. 建立连接
mongoConnStr="mongodb://cj:123456@localhost:27017/?authSource=admin"
client=pymongo.MongoClient(mongoConnStr)
print("list dbs:",client.list_database_names()) # 列出dbs
db=client['mg_test']
print("list collections of mg_test d... |
990,391 | c6cf062a9abbe57540bc0b758c6fb06cab8fc634 | # --------------
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
# code starts here
df = pd.read_csv(path)
print(df.head(5))
#Store features in X
y = df.iloc[:,1]
X = df.iloc[:,:9]
#X = X.drop('list_price', axis=1)
#print(X.head())
#Split dataframe
X_train, X_test, y_train, ... |
990,392 | 7fc828c37ff7b450d74078433c4d8fdcd8687ecb | from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.core.paginator import Paginator
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.views.generic import DetailView, CreateView, UpdateView, Dele... |
990,393 | efc64c773ff9e7c2049b82549be9861d78f926f8 |
btws = nx.betweenness_centrality(G)
sorted(btws.items(), key=lambda d:d[1], reverse=True) #you've seen this before
# Answer:
# IGF1 is the second most central in terms of betweenness
# also very visible from the histogram |
990,394 | f6829db0a04cd0f5973892f5ea012ef43fcda00d | print(9*9)
print(9+9)
print("Hello to spyder")
print(type(9))
print(type(9.2))
print(type("hello to spyder"))
|
990,395 | 08fd3f9b918a1503906dab53a12cba2df9ac0c9c | #!/usr/bin/env python
# -*- coding: ISO-8859-1 -*-
##################################
# @program synda
# @description climate models data transfer program
# @copyright Copyright “(c)2009 Centre National de la Recherche Scientifique CNRS.
# All Rights Reserved”
# @license... |
990,396 | 3bcc0ad2526c65730586cae7b065e1965ba3a813 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 22 20:14:48 2019
@author: Changze Han
"""
'''
For Flu:
Convert a cleaned fasta sequence(nucleotide or AA) file to a csv format file.
The purpose of this script is innovating a new way for fas->csv conversion.
Before today... |
990,397 | c9bc9af8684a9a5480a92d0ca74769535c64d90d | import torch
import time
from spherical_distortion.util import load_torch_img, torch2numpy
from spherical_distortion.transforms import CameraNormalization
import numpy as np
from skimage import io
import os
# Load the image and it's associated K matrix
os.makedirs('outputs', exist_ok=True)
img = load_torch_img('inputs... |
990,398 | 90d523835aabfd6a2c2048fa87deb2511eacb60c | """
STATEMENT
Given an array S integers and a target, find all unique quadruplets a, b, c, and d in S such that a + b + c + d = target.
CLARIFICATIONS
- Similar clarifications as 015-3sum.
EXAMPLES
[1, 0, -1, 0, -2, 2], 0 =>
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
"""
import collections
def two_sum(sum... |
990,399 | f6a88c9ec20812aadeba7b576a14d9d53668a877 | from calculos.calculos_generales import *
dividir(4, 6)
potencia(4, 6)
redondear(4/6) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.