index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
8,500 | e19529dce407da0f1e21f6a3696efcefac9ed040 | import pandas as pd
def load_covid():
covid = pd.read_csv("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv")
target = 'new_cases'
date = 'date'
dataset = covid[(covid['location'] == 'World')].copy()[[target, date]]
dataset[date] = pd.to_datetime(datase... |
8,501 | d3952306679d5a4dc6765a7afa19ce671ff4c0b4 | """
The :mod:`sklearn.experimental` module provides importable modules that enable
the use of experimental features or estimators.
The features and estimators that are experimental aren't subject to
deprecation cycles. Use them at your own risks!
"""
|
8,502 | bf45349a9fdfcef7392c477e089c5e3916cb4c8e | #!/usr/bin/python
# -*- coding: utf-8 -*-
import base64
import json
import os
import re
import subprocess
import time
import traceback
import zipfile
from datetime import datetime
import requests
from flask import request, current_app
from library.oss import oss_upload_monkey_package_picture
from public_config import... |
8,503 | 84d9400dc4ee0bebce3f5f7da0bd77a280bb54a9 | # Generated by Django 3.1.3 on 2020-11-27 02:17
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('foodBookApp', '0027_remove_post_total_comments'),
]
... |
8,504 | b5c68211cfa255e47ee316dc5b0627719eacae78 | # -*- coding: utf-8 -*-
from rest_framework import serializers
from django.contrib.auth.models import User
from core.models import Detalhe, Viagem, Hospital, Equipamento, Caixa
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = '__all__'
class CaixaSeri... |
8,505 | 1eb5df463bbd39002c5dbc3f88459e2f26d4b465 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-04-11 03:58
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('produksi', '0055_auto_20190409_1316'),
]
operations = [
migrations.R... |
8,506 | 89078ddd7dad3a2727b66566457b9ac173abe607 | from django.conf.urls import url, include
from . import views
explore_patterns = [
url(r'^$', views.explore),
url(r'^(?P<model_type>\w+)/$', views.get_by_model_type),
url(r'^(?P<model_type>\w+)/(?P<id>\w+)/$', views.get_by_model_id),
url(r'^(?P<model_type>\w+)/(?P<id>\w+)/download$', views.download_me... |
8,507 | dc41c64d09e5fdd0e234f516eeec0cbd2433876c | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 2 13:34:19 2020
@author: ShihaoYang
"""
from pyltp import SentenceSplitter
from pyltp import Segmentor
from pyltp import Postagger
from pyltp import Parser
from pyltp import NamedEntityRecognizer
import os
import jieba
import re
os.getcwd()
os.ch... |
8,508 | e103e7a215614e1a7923838b775f49bba2792036 | # -*- coding: utf-8 -*-
# Copyright 2014 Foxdog Studios
#
# 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 l... |
8,509 | 0b141ecca501c21df50e76d0841dd5651274f0da | from django import forms
from myapp.models import Student
from myapp.models import Employee
class EmpForm(forms.ModelForm):
class Meta:
model = Student
fields = "__all__"
class StudentForm(forms.Form):
firstname = forms.CharField(label="Enter first name:", max_length=50)
lastname = forms... |
8,510 | 534aaf8371707089522af014a93f3ff6c4f913ff | from django.contrib import admin
from pages.blog.models import Blog
admin.site.register(Blog)
|
8,511 | 21cfe1ca606d18763fbfb8ff6862c382b3321adc | # Copyright 2015 Cisco Systems, Inc.
#
# 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 in writing... |
8,512 | 69d3a39dc024929eaf6fb77e38a7a818d2886cf7 | '''
selection review
very similar to quicksort in terms of set up.
no need to sort to find kth element in a list
but instead can be done in o(n)
quick sort can be o(nlogn) if we choose median
instead of pivot
tips:
raise value error for bad index not in between 0 <= k < n
basecase of n <=1 --> return arr[0]
use L, E, ... |
8,513 | 57de9a46dfbf33b117c2dfbb534a5020e019d520 | # -*- coding: utf-8 -*-
"""
@Author: xiezizhe
@Date: 5/7/2020 下午8:52
"""
from typing import List
class KMP:
def partial(self, pattern):
""" Calculate partial match table: String -> [Int]"""
ret = [0]
for i in range(1, len(pattern)):
j = ret[i - 1]
while j > 0 and... |
8,514 | 62fc71e26ba3788513e5e52efc5f20453080837d | class Solution:
def projectionArea(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
res=0
for i in grid:
res+=max(i)
for j in i:
if j:
res+=1
for k in zip(*grid):
res+=max(k)
... |
8,515 | 324030a976af29dc93fdb637583bfaab93671cc2 | # Python 2.7 Doritobot Vision System
# EECS 498 Purple Team, 2014
# Written by Cody Hyman (hymanc@umich.edu)
# Written against OpenCV 3.0.0-alpha
import sys
import os
import cv2
import numpy as np
from uvcinterface import UVCInterface as uvc
from visionUtil import VisionUtil as vu
from collections import deque
from ... |
8,516 | 472cdca501890d1d07c7363a48532ed3a184727c | """This is a collection of utilities for httpy and httpy applications.
"""
import cgi
import linecache
import mimetypes
import os
import stat
import sys
from Cookie import SimpleCookie
from StringIO import StringIO
from urllib import unquote
from httpy.Response import Response
def uri_to_fs(config, resource_uri_pat... |
8,517 | 05d6f15102be41937febeb63ed66a77d3b0a678e | import time
import itertools
import re
from pyspark import SparkContext, SparkConf
from pyspark.rdd import portable_hash
from datetime import datetime
APP_NAME = 'in-shuffle-secondary-sort-compute'
INPUT_FILE = '/data/Taxi_Trips.csv.xsmall'
OUTPUT_DIR = '/data/output-in-shuffle-sort-compute-{timestamp}.txt'
COMMA_DE... |
8,518 | e00b81f73f4f639e008fde1a6b2d4f7937df4207 | #!/usr/bin/env python
host, port = "localhost", 9999
import os
import sys
import signal
import socket
import time
import select
from SocketServer import TCPServer
from SocketServer import StreamRequestHandler
class TimeoutException(Exception):
pass
def read_command(rfile,wfile,prompt):
def timeout_handler(signum... |
8,519 | 8921c0a17e90f7113d1e0be630a15fc9d74d1780 | from web3.auto.infura import w3
import json
import os
with open("contract_abi.json") as f:
info_json = json.load(f)
abi = info_json
mycontract = w3.eth.contract(address='0x091FDeb7990D3E00d13c31b81841d56b33164AD7', abi=abi)
myfilter = mycontract.events.currentResponderState.createFilter(fromBlock=16147303)
#myfilt... |
8,520 | db33f7386d1eacbfbfd29aa367df310c557ae864 | km=float(input())
cg=float(input())
print(round(km/cg,3),"km/l") |
8,521 | 329451a3d3fa95f5572dc1701d1adbf4aaa72628 | import argparse
from ags_save_parser import saved_game
def report_mismatch(compare_result_list):
report = []
for i in range(len(compare_result_list)):
value = compare_result_list[i]
if value != '_':
report.append((i, value))
return report
def report_mismatch_for_module(
... |
8,522 | 89ffb2da456d2edf15fde8adc01615a277c6caa1 | import numpy as np
import matplotlib.pyplot as plt
##########################################
# line plot
#########################################
# x축 생략시 x축은 0, 1, 2, 3이 됨
"""
plt.plot([1, 4, 9, 16])
plt.show()
"""
# x축과 y축 지정
"""
plt.plot([10, 20, 30, 40], [1, 4, 9, 16])
plt.show()
"""
# 스타일지정
# 색깔, 마커, 선 순서로 ... |
8,523 | 947055d1d6acc50e1722d79ea30e327414cd9c41 | N, D = map(int, input().split())
ans = 0
D2 = D*D
for i in range(N):
x, y = map(int, input().split())
if (x*x+y*y) <= D2:
ans += 1
print(ans)
|
8,524 | 719a993e1f5c5d1e803b04a5561373f2b9a5a5c2 | def get_perms(string):
toRtn = []
freq_table = count_letters(string)
get_perms_helper(freq_table, "", len(string), toRtn)
return toRtn
def count_letters(string):
freq = {}
for letter in string:
if letter not in freq:
freq[letter] = 0
freq[letter] += 1
return freq... |
8,525 | 2a9426653146603d9aa79a59ce181d97aa3c551c | import sys
input = sys.stdin.readline
N = int(input())
A, B, C, D = [], [], [], []
for i in range(N):
a, b, c, d = map(int, input().split())
A.append(a)
B.append(b)
C.append(c)
D.append(d)
AB = []
CD = []
for i in range(N):
for j in range(N):
AB.append(A[i] + B[j])
CD.append(C[... |
8,526 | 324081eb4e133f6d16e716f3119e4cbc5e045ede | import pytorch_lightning as pl
from matplotlib import pyplot as plt
class Model(pl.LightningModule):
def __init__(self, net):
super(Model, self).__init__()
self.net = net
self.save_hyperparameters()
self.criterion = None
self.optimizer = None
self.batch_loss_colle... |
8,527 | 7beb9d9e24f4c9a4e1a486048371da79c35d0927 | """
exercise 9-7-9-2
"""
fname = raw_input("Enter file name: ")
filehandle = open(fname)
d = dict()
for line in filehandle:
newline = line.split()
if newline != [] and newline[0] == 'From':
day = newline[2]
if day not in d:
d[day] = 1
else:
d[day] += 1
print d
|
8,528 | e83a9a4675e5beed938860037658d33c4d347b29 | class TestContext:
def test_should_get_variable_from_env(self, monkeypatch, fake_context):
expected = "test"
monkeypatch.setenv("SOURCE_PATH", expected)
actual = fake_context.get("SOURCE_PATH")
assert actual == expected
def test_should_get_variable_from_local_state(self, fake_co... |
8,529 | fd0db093b72dad4657d71788405fcca4ba55daff | __doc__ = """
Dataset Module Utilities - mostly for handling files and datasets
"""
import glob
import os
import random
from meshparty import mesh_io
# Datasets -----------------------
SVEN_BASE = "seungmount/research/svenmd"
NICK_BASE = "seungmount/research/Nick/"
BOTH_BASE = "seungmount/research/nick_and_sven"
DAT... |
8,530 | 47b40e4311f76cd620b7c6ed6b39216d866fa857 | import requests
import json
import hashlib
import os
def pull_from_solr(output_directory):
solr_url = 'http://54.191.81.42:8888/solr/collection1/select?q=*%3A*&wt=json&indent=true'
# TODO: ask about auth for this
req = requests.get(solr_url)
if req.status_code != 200:
raise
new_data = r... |
8,531 | 1da93e9113089f1a2881d4094180ba524d0d4a86 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Frame filtering
'''
import numpy as np
import cv2
def filter_frames(frames, method=cv2.HISTCMP_CORREL, target_size=(64, 64), threshold=0.65):
"""Filter noisy frames out
Args:
frames (list<numpy.ndarray[H, W, 3]>): video frames
method (int, o... |
8,532 | 5c12ff4f88af991fa275cd08adf3678ee4a678f3 | #!/usr/bin/python
#===============================================================================
#
# Board Data File Analyzer
#
# Copyright (c) 2017 by QUALCOMM Atheros, Incorporated.
# All Rights Reserved
# QUALCOMM Atheros Confidential and Proprietary
#
# Notifications and licenses are retained for attribution purp... |
8,533 | 315fe68f4adf39ded46fa9ad059fd2e962e46437 | import matplotlib.pyplot as plt
import numpy as np
from sklearn.utils import shuffle
import math
import vis_utils
class FLAGS(object):
image_height = 100
image_width = 100
image_channel = 1
CORRECT_ORIENTATION = True
class PrepareData():
def __init__(self):
... |
8,534 | c931d1ac5c2d003a8eaac3c6d777ce408df57117 | '''
Autor: Jazielinho
'''
import keyboard
from PIL import ImageGrab
import os
import tqdm
import random
from training import config_tr
class DataSet(object):
''' clase que crea dataset de entrenamiento '''
saltar = 'saltar'
nada = 'nada'
reglas = [saltar, nada]
formato = 'PNG'
train = 'trai... |
8,535 | 0b2bc19aea9393562f79df026bc17513e25c6604 | __author__ = 'Chitrang'
from google.appengine.api import memcache
from google.appengine.ext import db
import logging
import os
import jinja2
class User(db.Model):
id = db.StringProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
name =... |
8,536 | 89499ea8dd02d5e1b2ff635ab5203a65ceee4276 | import os
import codecs
import json
#~ from lxml import etree
import lxml.html
target = "test/index.html"
url = "http://de.wikipedia.org/wiki/Liste_von_Bergen_in_der_Schweiz"
command = "wget %s -O %s" % (url, target)
#~ os.popen(command)
f = open(target)
html = lxml.html.fromstring(f.read())
f.close()
tables = html.... |
8,537 | 99048ddb3f42382c8b8b435d832a45011a031cf1 | from .score_funcs import *
from cryptonita.fuzzy_set import FuzzySet
from cryptonita.helpers import are_bytes_or_fail
def scoring(msg, space, score_func, min_score=0.5, **score_func_params):
''' Run the score function over the given message and over a parametric
value x. Return all the values x as a Fuzz... |
8,538 | 503726cd2d70286189f4b8e02acaa3d5f6e29e12 | from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from . import models
class RegisterForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ("username", "email", "password1", "... |
8,539 | 773c217f7f76bd82ed3dabf7ae1aba1871f0932f | import requests
import unittest
import time
from common import HTMLTestReport
class Get(unittest.TestCase):
TMPTOKEN = ''
TOKEN = ''
def setUp(self):
pass
# 获取临时token,opterTmpToken
def test_gettmptoken(self):
url = 'https://jdapi.jd100.com/uc/core/v1/sys/opterTmpToken'
par... |
8,540 | e26f673dfae38148a56927ce82d5ea7ea2545e12 | x = 'From marquard@uct.ac.za'
print(x[8])
x = 'From marquard@uct.ac.za'
print(x[14:17])
greet = 'Hello Bob'
xa = "aaa"
print(greet.upper())
print(len('banana')*7)
data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
pos = data.find('.')
print(data[pos:pos+3])
stuff = dict()
print(stuff.get('candy',-1... |
8,541 | f32b9dc36b2452fea8c8f284fbf800f22608c3ae | import csv
import io
import pickle
import os
import pip
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaIoBaseDownload
import cv2
import numpy as np
SCOPES = ['https:/... |
8,542 | 0ca751e050244fd85c8110d02d5e7a79eb449ada | print('Hi, I am Nag')
|
8,543 | 274af2a0b758472ca4116f1dfa47069647babf57 | import seaborn as sns
tips = sns.load_dataset('iris')
sns.violinplot(x='species', y='sepal_length', data=tips, palette='rainbow')
|
8,544 | 7f21ab8d332d169226ef17276abbdd373e3a62c2 | import http.cookies
import json
import os
import itertools
import types
from framework import helpers
from framework import security
class Model:
"""Manages the information received by the client"""
def __init__(self):
"""Puth the os.environ dict into the namespace"""
self.__dict__.update(
... |
8,545 | 961bda96e433bb66d592ad1e99c92db0a9ab9fe9 | import os
import pandas as pd
import time
import sys
from tqdm import tqdm
sys.path.append(os.path.join(os.environ['HOME'],'Working/interaction/'))
from src.make import exec_gjf
from src.vdw import vdw_R, get_c_vec_vdw
from src.utils import get_E
import argparse
import numpy as np
from scipy import signal
i... |
8,546 | 11320922d24b27c5cfa714f88eb0a757deef987f | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License
from .attack_models import (DriftAttack, AdditiveGaussian, RandomGaussian,
BitFlipAttack, RandomSignFlipAttack)
from typing import Dict
def get_attack(attack_config: Dict):
if attack_config["attack_model"] == 'drif... |
8,547 | d08e4c85890dab7cb421fa994ef1947d8919d58f | # -*- coding: utf-8 -*-
# Item pipelines
import logging
import hashlib
from wsgiref.handlers import format_date_time
import time
import itertools
import psycopg2
from psycopg2.extensions import AsIs
from psycopg2.extras import Json
import requests
from scrapy import signals
from scrapy.pipelines.files import FilesPip... |
8,548 | 3caaa455cda0567b79ae063c777846157839d64f | from django.shortcuts import redirect, render
from users.models import CustomUser
from .models import Profile
def profile_page_view(request, username):
current_user = request.user
user = CustomUser.objects.get(username=username)
profile = Profile.objects.get(user=user)
if current_user in profile.follow... |
8,549 | 71ca67948100fb7ad388934740cead1ebe4a2b52 | ANCHO = 600
ALTO = 800
|
8,550 | 6065fae2a11f6b525ef10346e297505ec9d4e9d5 | import unittest
import numpy
import set_solver
class TestSets(unittest.TestCase):
def test_is_set(self):
"""Test set validator (Exercise 3a)."""
cards = numpy.array([[1,1,1,2,0],
[0,1,2,2,2],
[0,1,2,2,2],
[0,1,2... |
8,551 | 39ffb85fb10882041c2c9a81d796e7ff9df7d930 | # SPDX-FileCopyrightText: 2013 The glucometerutils Authors
#
# SPDX-License-Identifier: Unlicense
|
8,552 | 77b9b111cfb4d0b54e14b2aab81b7b05fd6bbccd | s = 'ejp mysljylc kd kxveddknmc re jsicpdrysirbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcdde kr kd eoya kw aej tysr re ujdr lkgc jv'
sa = 'our language is impossible to understandthere are twenty six factorial possibilitiesso it is okay if you want to just give up'
ans = {}
for i in range(len(s)):
ans[s[i]] = sa[i];
... |
8,553 | b4b2307897f64bb30cad2fbaaa1b320ae2aa7456 | # Generated by Django 2.1.5 on 2019-03-12 18:07
from django.db import migrations
def associate_experiments_to_organisms(apps, schema_editor):
"""Creates missing associations between experiments and organisms.
Based off of:
https://simpleisbetterthancomplex.com/tutorial/2017/09/26/how-to-create-django-da... |
8,554 | 9fa3a7c57b311a47e67de73bf6083f1f151d73f4 | from flask import Flask, render_template, request
import random, requests
app = Flask(__name__)
@app.route('/')
def hello():
# return 'Hello World'
return render_template('index.html')
# root 디렉토리에 있는 templates라는 폴더를 탐색하여 파일을 찾음
@app.route('/ace')
def ace():
return '불기둥!'
@app.route('/html')
def html... |
8,555 | f11ede752df7d9aff672eee4e230b109fcbf987b | # coding: gb18030
from setuptools import setup
setup(
name="qlquery",
version="1.0",
license="MIT",
packages=['qlquery'],
install_requires=[
'my-fake-useragent',
'requests',
'beautifulsoup4'
],
zip_safe=False
) |
8,556 | 5cf73e003b744b438c0db67ab39fb10a3f879f2f | import numpy as np
import math
class KMeans(object):
def __init__(self, data, option):
self.data = data
self.membership = None
self.centroids = None
self.option = option
self.temp_data = None
def fit(self, K):
data = np.asmatrix(self.data[0])
if self.o... |
8,557 | c9df53ac06b8bb106d73825d60fa885c06385e95 | import contextlib
import logging
import os
import pwd
import sys
from typing import Iterable
from sqlalchemy import Table, exists, null, select
from sqlalchemy.engine import Engine
from sqlalchemy.exc import DBAPIError
from sqlalchemy.pool import NullPool
from hades import constants
from hades.common import db
from h... |
8,558 | 0a5ea7ad0ee34c8a3f0299908c61fa0a09139d2f | #Diagonal Traverse
#Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal
order as shown in the below image.
#Example:
#Input:
#[
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ]
#]
#Output: [1,2,4,7,5,3,6,8,9]
#Explanation:
#Note:
# The total number of elements of the given... |
8,559 | addab37cb23abead2d9f77a65336cd6026c52c68 | #coding=utf-8
'''
find words and count
By @liuxingpuu
'''
import re
fin= open("example","r")
fout = open("reuslt.txt","w")
str=fin.read()
reObj = re.compile("\b?([a-zA-Z]+)\b?")
words = reObj.findall(str)
word_dict={}
for word in words:
if(word_dict.has_key(word)):
word_dict[word.lower()]=max(word_dict[wor... |
8,560 | 93418e554893db4eb888396e8d6f60a8364d9ee3 | #coding: utf-8
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^douban/books$', views.BookList.as_view()),
)
|
8,561 | 4c4275b96d3eceb5ff89a746c68d7f8736a1c2a5 | staff = ['инженер-конструктор Игорь', 'главный бухгалтер МАРИНА', 'токарь высшего разряда нИКОЛАй', 'директор аэлита']
def employee_name(name):
getting_a_name = name.split()
name_staff = getting_a_name[-1]
name_staff = name_staff.capitalize()
return name_staff
i = 0
while i < len(staff):
nam... |
8,562 | 631904ae96584bd19756f9335175a419397ac252 | from os import environ
import boto3
from flask import Flask, redirect
from flask_sqlalchemy import SQLAlchemy
from json import load
from pathlib import Path
path = Path(__file__).parent
db = SQLAlchemy()
with open(path / "../schemas.json", "r") as fp:
schemas = load(fp)
with open(path / "../config.json", "r"... |
8,563 | e41b5ee0dff30cca51593e737420889bce8f419f | """
Simple python script to help learn basic socket API
"""
import sys, socket
HOSTNAME = sys.argv[-2]
PORT = sys.argv[-1]
options = ( HOSTNAME, int(PORT) )
print options
print 'creating socket...'
sock = socket.socket()
print 'socket created'
print 'connecting...'
sock.connect(options)
print 'connected'
print 's... |
8,564 | bf764457e6af25d2d9406b18af51f63b36ab823a | import cv2 as cv
import numpy as np
import sys
from meio_tom_lib import *
imgname = sys.argv[1]
imgpath = "img/" + imgname
try:
img = cv.imread(imgpath)
newimg1 = jarvis_judice_ninke_1(img)*255
newimg2 = jarvis_judice_ninke_2(img)*255
cv.imshow("Imagem original",img)
cv.imshow("Jarvis, Judice e... |
8,565 | db31a69c57f773a79e5eaa8b3443b0366fd74861 | import random
from typing import List
from faker import Faker
from call_center.src.actors.agent import InsuranceAgent
from call_center.src.actors.consumer import Consumer
from call_center.src.common.person import (
AGE,
AVAILABLE,
INSURANCE_OPERATION,
PHONE_NUMBER,
INCOME,
CARS_COUNT,
KID... |
8,566 | 2332783c96b24caa383bf47d82384e1c40a48e94 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import copy
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _ut... |
8,567 | 2b3f8b1ac4735785683c00f6e6ced85d201de53f | from app01 import models
from rest_framework.views import APIView
# from api.utils.response import BaseResponse
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from api.serializers.course import DegreeCourseSerializer
# 查询所有学位课程
class DegreeCourseView(APIView):... |
8,568 | 065354d2a8fd8a75e16bf85f624b12641377029a | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 河北雪域网络科技有限公司 A.Star
# @contact: astar@snowland.ltd
# @site:
# @file: img_to_sketch.py
# @time: 2018/8/6 1:15
# @Software: PyCharm
from skimage.color import rgb2grey
import numpy as np
def sketch(img, threshold=15):
"""
素描画生成
param img: Image实例
... |
8,569 | ce8879dae6c7585a727e35f588722bc28045256a | # Ex 1
numbers = [10,20,30, 9,-12]
print("The sum of 'numbers' is:",sum(numbers))
# Ex 2
print("The largest of 'numbers' is:",max(numbers))
# Ex 3
print("The smallest of 'numbers' is:",min(numbers))
# Ex 4
for i in numbers:
if (i % 2 == 0):
print(i,"is even.")
# Ex 5
for i in numbers:
if (i > 0):
... |
8,570 | 797e7c1b3e8b41a167bfbedfb6a9449e6426ba22 | # -*- coding: utf-8 -*-
{
'name': 'EDC Analytic Entry',
'depends': [
'stock_account',
'purchase_stock',
'account_accountant',
],
"description": """
""",
'author': "Ejaftech",
'data': [
'views/account_move_view.xml',
],
}
|
8,571 | a52edeec62a6849bda7e5a5481fb6e3d7d9a4c6a | """Utilties to access a column and one field of a column if the column is composite."""
from typing import TYPE_CHECKING, Optional
from greenplumpython.db import Database
from greenplumpython.expr import Expr
from greenplumpython.type import DataType
if TYPE_CHECKING:
from greenplumpython.dataframe import DataFra... |
8,572 | 51a8b963047215bf864eb4a3e62beb5741dfbafe | class Graph():
def __init__(self, nvertices):
self.N = nvertices
self.graph = [[0 for column in range(nvertices)]
for row in range(nvertices)]
self.V = ['0' for column in range(nvertices)]
def nameVertex(self):
for i in range(self.N):
pr... |
8,573 | db46fbfb1acd855eebb5c9f557d70038b84e812d | import surname_common as sc
from sklearn.utils import shuffle
import glob
import os
import re
import pprint
import pandas as pd
import unicodedata
import string
def unicode_to_ascii(s):
return ''.join(
c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn' and c in sc.ALL_LE... |
8,574 | c20a414f7f96a96f6e458fc27e5d2c7ac7ab05cf | def ispalindrome(s):
if len(s) <= 1:
return True
elif s[0] != s[-1]:
return False
else:
return ispalindrome(s[1:-1]) |
8,575 | 866ff68744a16158b7917ca6defc35440208ae71 | from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from polls.models import Poll
from .serializers import PollSerializer
# class PollView(APIView):
#
# def get(self, request):
# serializer = PollSeri... |
8,576 | bdda42665acfefccad45a2b49f5436a186140579 | class people:
def __init__(self, name):
self.name = name
self.purchase_descrip = []
self.purchase_price_descrip = []
self.purchases = []
self.total_spent = 0
self.debt = 0
self.debt_temp = 0
self.pay = []
self.pay_out = []
self.pay_who... |
8,577 | 1f86fe72c90c8457715a2f400dae8d355a9a97cf | from HiddenLayer import HiddenLayer
from Vector import Vector
import IO
import Loss
import Utils
import Activation
import Backpropagation
import Rate
# As a test, let's simulate the OR-gate with a single perceptron
""" training = []
training.append(Vector(2, arr=[1, 1]))
training.append(Vector(2, arr=[1, 0]))
trainin... |
8,578 | 18789b5106d4be8a02197b165e16a74c08a58c66 | import math
def sexpr_key(s_expr):
return s_expr.strip('(').split(' ')[0]
def expr_key(expr):
return expr.split(' ')[0]
def expr_data(expr):
return expr.split(' ')[1:]
def list_key(_list):
if type(_list) is type(list()):
return _list[0]
else:
return expr_key(_list)
def ... |
8,579 | fc20a2bf09d510892a4d144fbbd2cb2012c3ad98 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'FormHello.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, Qt... |
8,580 | 4282303e3e6ee122f1379bea73c619870f983f61 | age=int(input('请输入您的年龄:'))
subject=input('请输入您的专业:')
college=input('请输入您是否毕业于重点大学:(是/不是)')
if (subject=='电子信息工程' and age>25) or (subject=='电子信息工程' and college=='是') or (age<28 and subject=='计算机'):
print('恭喜您被录取!')
else:
print('抱歉,您未达到面试要求')
|
8,581 | 47259844f76f12060f0cf52f1086c05b9f300175 | def firstDuplicate(array):
"""
Time O(n) | Space O(n)
"""
dic = {}
for num in array:
if num in dic:
return num
else:
dic[num] = True
return -1
print(firstDuplicate([2,1,3,5,3])) |
8,582 | f9ea29f882c6491a2ac0007e4d9435c732d0967a | import math
import numpy
import theano
from theano import tensor as T
from utils import shared_dataset
from layer import HiddenLayer, LogisticRegressionLayer
import pickle as pkl
from mlp import MLP, Costs, NeuralActivations
DEBUGGING = False
class PostMLP(MLP):
"""Post training:- Second phase MLP.
A mul... |
8,583 | 03a1f9f533f7550db32fa25578ef2f7f4c741510 | # !/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: sx
import string
def reverse(text):
"""将字符串翻转"""
return text[::-1]
def is_palindrome(text):
print(e for e in text if e.isalnum())
# 去掉标点空格
m = ''.join(e for e in text if e.isalnum())
print(m)
"""是否是回文数"""
return m == revers... |
8,584 | cc19ff829cc4a11c3dc873353fa2194ec9a87718 | import os
from PIL import Image
import cv2
import shutil
root = './train'
save_path = './thumbnail'
for r, d, files in os.walk(root):
if files != []:
for i in files:
fp = os.path.join(r, i)
label = i.split('_')[0]
dst = os.path.join(save_path, label)
if not o... |
8,585 | 707e3e60d6d9a3db5b9bc733e912b34e2cec5974 | from .models import RecommendedArtifact
from .serializers import RecommendedArtifactSerialize
from rest_framework.decorators import api_view
from rest_framework.response import Response
from datetime import datetime
import requests, bs4
# constant value
service_key = "{jo's museum key}"
@api_view(['GET'])
def artifa... |
8,586 | 5a4a014d07cf312f148e089ea43484f663ce32bc | import requests
from bs4 import BeautifulSoup
import re
# if no using some headers, wikiloc answers HTML error 503, probably they protect their servers against scrapping
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0',}
def main():
print("################... |
8,587 | e3a59a1ae65dd86ff2f5dcc15d4df9e8dc451990 | def is_prime(x):
divisor = 2
while divisor <= x**(1/2.0):
if x % divisor == 0:
return False
divisor += 1
return True
for j in range(int(raw_input())):
a, b = map(int, raw_input().split())
count = 0
if a == 2:
a += 1
count += 1
elif... |
8,588 | 45d5c75a993ff50e1a88510bdb16e963403c5356 | # Tip Calculator
# Dan Soloha
# 9/12/2019
total = int(input("What was the total your bill came to? "))
print(f"With a total of {total}, you should tip ${int(total + (total * 0.15))}. If the waiter did a really good job, you should tip ${int(total + (total * 0.20))}. ") # Multiplying by 1.x was returning the numb... |
8,589 | 2ec5e43860a1d248a2f5cd1abc26676342275425 | from django.shortcuts import render, redirect
from django.utils.crypto import get_random_string
def index(request):
if not "word" in request.session:
request.session["word"] = 'Empty'
if not "count" in request.session:
request.session["count"] = 0
if request.method == "GET":
return... |
8,590 | 80531ac3cc247d48ee36bff581925b8f29f9e235 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
import numpy as np
import time
import os
import csv
import matplotlib.pyplot as plt
from GELu import GELu
from My_Dataset import MyDataset
from pytorchtools import EarlyStopping
from LSTM import LSTM
'''
Wr... |
8,591 | dffcaf47ec8e0daa940e7047f11681ef3eabc772 | import sys, os
class Extractor:
def __init__(self, prefix=''):
self.variables = {}
self.prefix = os.path.basename(prefix)
'''
Returns the variable name if a variable with
the value <value> is found.
'''
def find_variable_name(self, value):
for var, val in self.v... |
8,592 | b3f4815495c781fe6cc15f77b4ee601680117419 | from ctypes import *
class GF_IPMPX_Data(Structure):
_fields_=[
("tag", c_char),
("Version", c_char),
("dataID", c_char)
] |
8,593 | 8787126e654808a5fec52283780d9b4f668fa50f | import Numberjack as Nj
class Teachers(object):
"""Will be expanded to allow constraints for individual teachers"""
def __init__(self):
self.store = list()
def add(self, teachers):
if isinstance(teachers, (list, tuple)):
self.store.extend(teachers)
elif isinstance(teac... |
8,594 | 2317a2fff493588ad6cc3a4ac2b600fbf1c5583c | import numpy as np
import dl_style_transfer.workspace.data_helpers
import os
here = os.path.dirname(os.path.abspath(__file__))
sents = list(open(os.path.join(here, 'yelp_sentences.txt'))) + list(open(os.path.join(here, 'shake_sentences.txt')))
thresh = 5
col = dict()
word_to_ind = dict()
ind_to_word = dict()
def... |
8,595 | 5f471fb75b1c4f6fc7aa4cb4f99f9c1a1a9f0ea1 | import pytest
from chess.board import Board, ImpossibleMove
from chess.pieces import King, Rook, Pawn, Knight
def test_board_has_32_pieces():
board = Board()
assert board.pieces_quantity() == 32
def test_board_can_be_instatiated_with_any_set_of_pieces():
board = Board(initial_pieces={'a2': Pawn('white'... |
8,596 | 7c65d0bdd4fd808b3d87706357a651601368e43b | import os
from unittest import TestCase
from pyfibre.gui.file_display_pane import FileDisplayPane
from pyfibre.tests.fixtures import (
directory,
test_image_path)
from pyfibre.tests.probe_classes.parsers import ProbeParser
from pyfibre.tests.probe_classes.readers import ProbeMultiImageReader
source_dir = os.p... |
8,597 | 88a379747f955b0410ab2bb33c1165034c701673 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'wenchao.hao'
"""
data.guid package.
"""
from .guid import Guid
|
8,598 | 360881cecbad88ea5d150548fba6a39d8dc30681 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
db = {
'host': "localhost",
'user': "root",
'passwd': "m74e71",
'database': "dw_toner"
}
data_inicial = '1990-01-01'
ano_final = 2018
feriados = "feriados.csv"
meses_de_ferias = (1, 2, 7, 12) #Janeiro, Fevereiro, Julho, Dezembro
dias_final_semana = (1, ... |
8,599 | 9e21a39358d97633b49ad83805990c29c19a80ed | import argparse
import glob
import importlib
import inspect
import math
import os
import re
import subprocess
import sys
import moviepy.audio.fx.all as afx
import moviepy.video.fx.all as vfx
import numpy as np
from _appmanager import get_executable
from _shutil import format_time, get_time_str, getch, print2
from movi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.