index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
998,900 | 5f5f46757c83a3e6fdc1ea6f3333707fe0d1fee5 | import sys
import getcred as gc
def createSheet(spreadsheet_id, sheetName):
batch_update_spreadsheet_request_body = {
'requests': [
{
'addSheet': {
'properties': {
'title': sheetName
}
}
... |
998,901 | 8538ae51085c6debdd1fc582ccb4d57679670b23 |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time
import os
import wget
PATH = 'D:\Code\python\crawler\chromed... |
998,902 | c5c3b0c1709108ab55da4e6ec65b15ee80e17909 | from django.conf import settings
DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG', {
'convert_urls': False,
'height': '350',
'theme': 'advanced',
'plugins': 'advimage,advlink,fullscreen,media,safari,table,paste',
'theme_advanced_toolbar_location': 'top',
'theme_advanced_buttons1': '... |
998,903 | 1e36a9b1e6fb05d7661631a6ca3a4262beef2706 | # coding=utf-8
COUNT=0
def perm(n,begin,end):
global COUNT
if begin>=end:
for i in n:
print(i,end=" ")
print()
COUNT +=1
else:
i=begin
for num in range(begin,end):
n[num],n[i]=n[i],n[num]
perm(n,begin+1,end)
n[num],n[i]=... |
998,904 | 2a9f578670f812bff5fd552995e85a22dd3e06cb | from operator import attrgetter
class Users:
def __init__(self,x,y):
self.name = x
self.user_id = y
def __repr__(self):
return self.name + " : "+str(self.user_id)
users = [
Users('Chris',67),
Users('Ankita',34),
Users('Phil',5),
Users('Christina',90),
Users('Mo',56... |
998,905 | 69f4b7cd8d888d0f5bfc8817c4f7905c36a88b2d | ###import statements
import nltk
from collections import defaultdict
import operator
from collections import OrderedDict
from operator import itemgetter
from nltk.stem.lancaster import LancasterStemmer
from collections import Counter
import pandas as pd
###function_words:
##input: string with all word... |
998,906 | 85aec9fd783f7f62c5fcf820c984e9cac3f691af | '''
Quick Note:
This search is by no means perfect and thorough. I have applied
4 cv strategies and theoretically they should be having their
own optimal parameters. However, that process is way too slow.
Here is a quick computation. For this problem we need ~4 minutes
to grow a tree. For ... |
998,907 | 5ecf52b0abe86aa84c58c6c0d16f863de1c789ab | import keras
import os
# two classes
num_classes = 2
# Y_train.shape = (num, 1) -> y_train.shape = (num, 2)
y_train = keras.utils.to_categorical(Y_train, num_classes)
y_test = keras.utils.to_categorical(Y_test, num_classes)
def myKerasModel():
# input_shape should be the shape without example dim.
# e.g. X_t... |
998,908 | e6a499bca3bcd595bf84abfae7dea180d2d52e92 | WS_PORT = 8856 # Port http server will run on
SCHEMA_LOCAL = "/usr/share/ipp-connectionmanagement/schemas/"
|
998,909 | 913c11de08434565872c655e143ffca63446d4b0 | import os
import numpy as np
import random
from shutil import copyfile, copytree
import sys
sys.path.insert(0, '/home/docker/2017-tfm-nuria-oyaga')
from Utils import utils
if __name__ == '__main__':
# General parameters
base_path = "/home/docker/data_far_50/Frames_dataset"
to_mix = ["linear_point_255_var... |
998,910 | 7b8bf1ab9fb4aec6977df34ebe92e92b8c24612a | import json
import os
from time import sleep
from models.result_types import ResultType
from processing import pipeline_zoo
from processing.basic_pipelines import MergePipelineStep, OutputPipelineStep, SplitPipelineStep
from processing.output.file_output_pipeline import FileOutputPipeline
from processing.pipeline_zoo ... |
998,911 | 4d4db6fcd77154604ee44978bad9a59af4db1797 | import logging
import shutil
import os
from rest_framework import mixins
from rest_framework import viewsets
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.decorators impor... |
998,912 | bfa70c449d93d6b19ea8a46c0e604ec610515d4a | from django.contrib.auth.models import User
from tastypie import fields
from tastypie.authorization import Authorization
from tastypie.resources import ModelResource
import butternut.account.api as AccountAPI
from models import Match
import datetime
class MatchResource(ModelResource):
winner = fields.ForeignKey(A... |
998,913 | 3cc85aee5cd82f213d3ef2eace078662b2cc5494 | from dataclasses import dataclass, is_dataclass
from tkinter import *
from tkinter.ttk import *
from typing import Union
@dataclass
class NetworkSettings:
network_settings: Widget
gradient_multiplier: Union[DoubleVar, None] = None
selection_method: Union[StringVar, None] = None
def __post_init__(self... |
998,914 | 61f02f7b2fd90918e75498200d8310602b9ac1a7 | import time
import copy
import sys
import a3dc_module_interface as a3
from modules.packages.a3dc.utils import error, warning
from modules.packages.a3dc.ImageClass import VividImage
from modules.packages.a3dc.constants import SEPARATOR
def module_main(ctx):
try:
#Inizialization
tstart = time.clock(... |
998,915 | 6e314590828dccd434eb65de23b8652070f485c1 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 16:15:28 2019
Predictions with models of type Ratings and Genres with Chronological Data
@author: nicholas
"""
######## IMPORTS ########
import sys
import json
import torch
import numpy as np
import matplotlib.pyplot as plt
# Personnal ... |
998,916 | 9425a7a69684cec9583621dff27b961ddf3ea146 | """
faster_rcnn_chainercv
train_SUNRGBD
created by Kazunari on 2018/06/26
"""
from __future__ import division
import argparse
import numpy as np
import os.path as osp
import datetime
import matplotlib
matplotlib.use('Agg')
import chainer
from chainer.datasets import TransformDataset
from chainer import training
f... |
998,917 | cba7d08af2b3ab07bc39b55c5f748f77f9dcdd35 | import pytest
from phub_crypto import PhubCrypto
class TestPhubCrypto:
def test_init(self):
crypto = PhubCrypto(b'saltsalt', 'badpass')
assert crypto
def test_encrypt_decrypt(self):
crypto = PhubCrypto(b'saltsalt', 'badpass')
target = "This is the target string"
ciphe... |
998,918 | dd5426f1bc7c81bf9807d4178cbd9b38aaaa4c4b | import numpy as np
import matplotlib.pyplot as plt
def Euclid_norm(x):
norm = 0
for i in x:
norm += i**2
return np.sqrt(norm)
def scalar(x, y):
sc = 0
for i in range(len(x)):
sc += x[i]*y[i]
return sc
if __name__ == "__main__":
a = 1
b = 1.2
n = 10
h = 1/n... |
998,919 | 3db8a1625d846ea0d3d0e3184ef4af0964c188b1 | from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.response import Response
from rest_framework import status
from Discussion_Forum.models import Post
from .serializers import PostSerializer, ResultSerializer
from rest_framework.decorators import api_view
from ... |
998,920 | 4b3b97e59a62c67b7cf20d68e3029e38b11054dd | #!/usr/bin/env python
"""
File: normalize.py
Date: 5/8/18
Author: Jon Deaton (jdeaton@stanford.edu)
"""
import sys
sys.path.append('..')
print(sys.path)
import argparse
import multiprocessing as mp
import BraTS
from BraTS.structure import *
from normalization import normalize_patient_images
import logging
pool_s... |
998,921 | 93d0bd5ef130e4340ed39b6dd7f43d38860034ac |
class Scene():
def __init__(self,guid,name,control_channel_guid):
self.guid = guid
self.name = name
self.control_channel_guid = control_channel_guid |
998,922 | bf3f82ce5532d4578fad0039f5edfcc6c5af133c | import sched, time
from Analytics import Analytics
from datetime import datetime
import os
from analyticConfigs import config
scheduler_obj = sched.scheduler(time.time, time.sleep)
def start_App(sc):
print("******************************************* Job Started at {} **".format(datetime.now()))
Analytics(... |
998,923 | e8c6522bab1db58b3e3def517f156cef212419b3 | # -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Nov 6 2013)
## http://www.wxformbuilder.org/
##
## PLEASE DO "NOT" EDIT THIS FILE!
###########################################################################
impo... |
998,924 | 9c24d5938628d7accec0537cb0d3e1d95e3157f5 | #将一个列表的数据复制到另一个列表中。
l1 = []
i = 0
while i <= 9:
a = input('请输入10个数据:')
l1.append(a)
i += 1
l2 = l1[:]
print('原先的列表是:{}')
print('复制出来的数据是:{}'.format(l2))
|
998,925 | dac62c3994ffccb5f064e4a7503388240cab2b60 | from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class Profile(models.Model):
city = models.ForeignKey("City", null=True, on_delete=models.CASCADE)
phone_number = models.CharFi... |
998,926 | 5dda4d2a6ff3abd19e23ec590f3a92a499525f49 | #! /usr/bin/python
import os
import argparse
import sys
import get_GFSX025_grib2 as grib
from datetime import datetime, timedelta
import time
# Default values. Editable by user
MAX_OFFSET = 168 # MAX_OFFSET == 168hs(7 days)
MIN_NODES_AMOUNT = 2
MAX_NODES_AMOUNT = 9
SEPARATOR = '-' * 80
def update_namelist_... |
998,927 | f852a029ed501c9b99422b3db96e062d241646bb | import re,json
raw_html = open("coursesearch.html", "r").read()
#html_regex = "<OPTION VALUE=\"(.*)\">(.*)"
html_regex = "<option value=\"(.*)\">(.*)"
schools_raw = re.findall(html_regex,raw_html)
schools = []
for school_raw in schools_raw:
school = {}
school["name"] = school_raw[0]
school["title"] = school_raw... |
998,928 | 3f419b101d145deb6b89d0d6dec3b1833d2e33da | if __name__ == '__main__':
a = int(input())
b = int(input())
c1=a+b
c2=a-b
c3=a*b
print(c1)
print(c2)
print(c3)
|
998,929 | d6b1e080ca9c1ad7162735660ec008c4edd5eeff | class ET:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
def isOperator(c):
if (c=='+' or c=='-' or c=='*' or c=='/' or c=='^'):
return True
return False
def inorder(t):
if t is not None:
inorder(self.left)
print(t.value)... |
998,930 | dc53b5eedd83f6b1c9b1ef49b4354ae6cbee995f | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
people = num_people * [0]
give = 0
while candies > 0:
people[give % num_people] = people[give % num_people] + min(candies, give + 1)
give = give + 1
candies = c... |
998,931 | ff8e4723a2a6745dcfc9c8c462968d53ea1aebb6 | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from ..azure_common import BaseTest, arm_template
from c7n_azure.session import Session
from c7n.utils import local_session
from mock import patch
class ResourceGroupTest(BaseTest):
def setUp(self):
super(ResourceGroupTest, sel... |
998,932 | 47a4704b8c1fba8c073db28bf6b41d475062d66d | import os
import PIL.Image
import PIL.ImageOps
import numpy as np
count = 0
def exif_transpose(img, file):
global count
if not img:
return img
count += 1
exif_orientation_tag = 274
# Check for EXIF data (only present on some files)
if hasattr(img, "_getexif") and isinstance(img._getex... |
998,933 | 15817ce861bffa2b8718bd1a71e20c3dc4e8d827 | from teacherbot.bot import bot
|
998,934 | 4aef6fb48a8bfa1ba1fec806348839c5eb69ed6f | '''
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your returned answers (both inde... |
998,935 | 7008b4c43731306002ba5144d15a726b30c7d37e | # ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.7.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# # P... |
998,936 | 965ad26dd23ca2cc3537ca491aa3eb2d88be1e9d | '''
this is the file for reading in audio inputs and processing them into MFCCs
'''
import fnmatch
import os
import random
import numpy as np
# from python_speech_features import mfcc
import librosa.feature
import scipy.io.wavfile as wav
from scipy.io.wavfile import write as wav_write
import librosa
# make mfcc np ar... |
998,937 | 97d9f07e40a09f7b178c6a235bd9c06f8d2756cf | from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Book, Rating
from rest_framework.authtoken.views import Token
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'password']
# to hid ... |
998,938 | a519977c634bf1bdcb371496f2155533da600d10 | from django.contrib import admin
from django.urls import path
from .views import home, API_used, contact
from django.views.static import serve
from django.conf.urls.static import static
from django.conf.urls.static import url
urlpatterns = [
path('', home, name="home"),
path('api/', API_used, name="api"),
... |
998,939 | caddf2857cdc59884382adce38cc85f7fa3e94fa | from flask import Flask, render_template, g, request, session, redirect, url_for
from database import get_db
from werkzeug.security import generate_password_hash, check_password_hash
import os
app = Flask(__name__)
@app.teardown_appcontext
def close_db(error):
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
@app... |
998,940 | b199ebdca374b3c059b7ca2ef29c3570c4ecdc66 | from metadata_driver_mongodb import plugin
__author__ = """Nevermined"""
__version__ = '0.1.0'
|
998,941 | 55ae06c520ff11f386a407dbb4c37375731ce057 | import os
import keras
import math
import threading
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
import pandas as pd
import numpy as np
class DataGenerator(keras.utils.Sequence):
"""Generates data for Keras."""
def __init__(self, imgs_dir, metadata_dataframe,... |
998,942 | 7c9e7ca42decfc20e5ffa8722cc9acab747cf6f2 | # -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Test matcher
# ---------------------------------------------------------------------
# Copyright (C) 2007-2017 The NOC Project
# See LICENSE for details
# -------------------------------------------------------------------... |
998,943 | e824acc82b083e6dde558ebcf51602616c3a0831 | squares = [1, 4, 9, 16, 25]
print("当前列表是: ", squares)
# 注意:
# 所有的切片操作都返回一个新列表, 这个新列表包含所需要的元素。就是说,如下的切片会返回列表的一个新的(浅)拷贝:
print('类似字符串列表也支持切片操作,返回一个子列表: ', squares[0: 2])
squares.append(36)
print("在列表末尾添加新元素: ", squares)
# i = int(input("请输入一个正整数:"))
i = squares[0]
if i < 10:
print("这是一个一位数: ", i)
elif i == 10... |
998,944 | 31838d2950825569ecc33ca1d2417a9d19a5fb99 | import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from channels.consumer import AsyncConsumer
import time
import asyncio
class ChatConsumer(AsyncConsumer):
async def websocket_connect(self, event):
print("connected", event)
await self.send({... |
998,945 | b22698777640a5c5d9cca5c6e9bfc13ef789abe1 | #coding=utf-8
import os
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import pickle
import pandas as pd
import numpy as np
from glob import glob
from sklearn.neighbors import NearestNeighbors
from config import *
df = pd.read_csv('../train.csv')
train_files = [f for f in df.images.values]
file_id_mapping ... |
998,946 | 39abf81d9d579a8959478e181dec42e312ba3f2d | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class Liblognorm(AutotoolsPackage):
"""Liblognorm is a fast-samples based normalization ... |
998,947 | 27d11e02a2f3ac102b7a793f1df48a954f2b770c | # Generated by Django 2.2.6 on 2019-12-01 05:11
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swa... |
998,948 | 40cbfa66826a1f34434bc0290d1686b5550f2591 | email = 'aunghtetpaing@berkeley.edu'
def schedule(treasury, sum_to, max_digit):
"""
A 'treasury' is a string which contains either digits or '?'s.
A 'completion' of a treasury is a string that is the same as treasury, except
with digits replacing each of the '?'s.
Your task in this question is to... |
998,949 | bd44ad20908105309b35614667f01820c569cb8f | infile=open('acadin.txt','r').readlines()
a,b=0,0
for e in infile:
i=e.strip()
if i=='i':
a+=1
elif i=='o':
b+=1
if i=='x':
break
total=max(0,a-b)
outfile=open('acadout.txt','w')
outfile.write(str(total))
outfile.close()
|
998,950 | 4de26093cb6a0a89ef75eb9379f4130200198210 | import psycopg2
import psycopg2.errorcodes
import csv
import datetime
import itertools
#Здійснюємо з'єднання з БД
con = psycopg2.connect(
database="lab1", user='postgres', password='123456789', host='127.0.0.1', port= '5432')
cur = con.cursor()
#Видаляємо таблицю в разі її існування
cur.execute("DROP... |
998,951 | 82bf52b2624597b5db43b3195f8d9fc4c17f6d90 | import unittest
from django.urls import reverse
from django.test import Client
from .models import University, Course, Subject
from django.contrib.auth.models import User
from django.contrib.auth.models import Group
from django.contrib.contenttypes.models import ContentType
def create_django_contrib_auth_models_user(... |
998,952 | 4098fa1cfc8176b22603aec502902f3b2af9d954 | from fedwriter import FedWriter
from selenium import webdriver
import sys
import csv
from businessstarts import BlsCount
from businessstarts import BusStarts
import businessdata
import os
import time
import requests as req, xml.etree.ElementTree as ET, pandas as pd
payload = {'period':'2016-Q3','industry':'10','ow... |
998,953 | e03bb58b24774d695efaaa1e9efd72944748a01d | from .. import errors
from .. import utils
from ..types import CancellableStream
class ExecApiMixin:
@utils.check_resource('container')
def exec_create(self, container, cmd, stdout=True, stderr=True,
stdin=False, tty=False, privileged=False, user='',
environment=None, w... |
998,954 | 0cd24eb0955837430cb1138ff23902343ff1c59a | import site
from dev_appserver import EXTRA_PATHS
for pth in EXTRA_PATHS:
site.addsitedir(pth)
|
998,955 | 1ce8c3869268a21e613e9d8eaa3d38ddde1c3c98 | import argparse
import sys
import pandas as pd
import numpy as np
import random
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow_addons.metrics import FBetaScore
from tensorflow.keras import optimizers, callbacks, Model
from tensorflow.data.experimental import AUTOTUNE
from tqdm.auto import t... |
998,956 | b856b56c86de7365ef46fd386273c3b802547f02 | shopping_list = ['watch', 'bag', 'perfume', 'shoes', 'bikini']
while True:
steps = ['C','R','U','D']
for index1, value1 in enumerate(steps):
print(index1+1, value1)
value1 = input('What steps you want to do?')
if value1 == 'C':
name = 'heels'
shopping_list.append(... |
998,957 | bfa65c04c784da5ef607cb7671cbb400c6943164 | # scaling factors
scale_factors = {'no_spine_scale' : 1.0, 'basal_scale' : 2.7, 'med_spine_rad_scale' : 1.2,
'med_spine_LM_scale' : 1.1, 'max_spine_rad_scale' : 1.6,
'thin_rad_spine_scale' : 2.6, 'thin_LM_spine_scale' : 1.2}
# Primary apical list
prim_apical = [
'somaA',
'dendA5_0',
'dendA5_01',
'dendA5_011',
'd... |
998,958 | d560f08941eaa5babdb34b43aea2872e8b74b1f9 | from .stanza import Stanza
class FrontendStanza(Stanza):
"""
Stanza subclass representing a "frontend" stanza.
A frontend stanza defines an address to bind to an a backend to route
traffic to. A cluster can defined custom lines via a "frontend" entry
in their haproxy config dictionary.
"""
... |
998,959 | 251a763a33bd859b4f4192a6e82f59acd2ecbc42 | import cv2 as cv
import numpy as np
# "C:\school\fydp\opencvTut\opencv-course\Resources\Photos\cat.jpg"
resourcesFolder = "Resources\\"
img = cv.imread(resourcesFolder+'\\Photos\\park.jpg')
cv.imshow('park',img) # display image
# about color channels : b,r,g can split into individual
blank = np.zeros(img.shape[:2],... |
998,960 | c96d215533e7e6defd7e1bfee319faf4fa02a83e | import wx
import time
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None,-1,"多模测试热补丁工具",size = (800,600))
panel = wx.Panel(self)
list1 = ["BPN2","BPL1" ,"BPC"]
list2 = ["RRU1", "RRU2", "RRU3"]
#ListBox类实例
self.listbox1 = w... |
998,961 | 062ee7adbb07c9483c5f269c8667f09ed24f60b5 | import dominions
import util
import urllib2
import json
link, install, uninstall = util.LinkSet().triple()
CONF_PATH = 'conf/dominions_discord.py'
USER_AGENT = 'PageBot (https://github.com/joodicator/pagebot, 1.0)'
def required_class_attr(attr_name):
def get_required_class_attr(self):
raise util.UserErro... |
998,962 | f73fdca180fdb28f889cbb7deedf8458df8b461a | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
task.py
调整代码可以把Paul和Bart都正确删除掉
'''
L = ['Adam', 'Lisa', 'Paul', 'Bart']
print '删除元素Paul:', L.pop(2)
print '删除Paul元素,后列表为:', L
print '删除元素Bart', L.pop(2)
print '删除Bart元素,后列表为:', L
|
998,963 | 2af627123cf2c2a81c50c2d11022517924eb27f6 | import mnist_softmax # NOQA
import numerai_softmax # NOQA
|
998,964 | 0a5dcca67afe2356bc33309eaaaada89be7ea8dc | '''
while lykkja
input frá notenda sett inn í lista
endar while lykkju ef tala er neikvæð
Kíkja á lista eftir for lykkju og finna stærstu töluna með max fallinu
'''
number_list = []
num_int = 0
while num_int >= 0:
num_int = int(input("Input a number: ")) # Do not change this line
... |
998,965 | f813d755670c9e777f6b406875be362b38d986d1 | # Copyright 2019 DTAI Research Group - KU Leuven.
# License: Apache License 2.0
# Author: Laurens Devos
name = "bitboost"
from .sklearn import BitBoost, BitBoostRegressor, BitBoostClassifier
__author__ = "Laurens Devos"
__copyright__ = "Copyright 2019 DTAI Research Group - KU Leuven"
__license__ = "Apache License 2.... |
998,966 | fffc8362b214f3aba16e5f044a83a192f19d3e43 | from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render, redirect
from .models import Following, Image, Profile
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.urls import reverse
# Create your views here.
@login_requi... |
998,967 | 2a11ec20d9155c5c2dbe1818befb6f67359557e7 | from django.shortcuts import render
from django.http import HttpResponse
from .forms import UserForm
import re
import numpy as np
import pickle
from sklearn.linear_model import LogisticRegression
def index(request):
if request.method == "POST":
review = request.POST.get("review")
rev_s = text_tran... |
998,968 | de7154133df5f458975b02a242c2aa1c4f75d5cc | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import glob
import time
import json
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from torch.utils.tensorboard import SummaryWriter
import tensorflow as tf
import tensorboard as tb
tf.io.gfile = tb.compat.tensorflow_stub.io.gfile
import ba... |
998,969 | 9f17b9c78696184bdbce94be761fffe120693d15 | import os
def normal_users(user,ord):
if ord[0] == 'send mail':
to = ord[1]
if type(ord[2]) == str:
msg = ord[2]
else:
msg = str(ord[2])
try:
path = os.getcwd() +'/'+to
if not os.path.exists(path):
msg =("Could'n send a... |
998,970 | b5bd5dc10f6145fc5242eaff72f3d23271a7feb3 | __doc__ = """
DaetTools model that describes the behavior of a water flowing in a pipe with the effect of biofim formation.
"""
from daetools.pyDAE import *
from pyUnits import m, kg, s, K, Pa, J, W, rad
import pandas as pd
try:
from models.external_film_condensation_pipe import ExternalFilmCondensationPipe
... |
998,971 | 06595596ce534399e6293bc766bdd66e7b75b4ff | #!/usr/bin/python
# -*- coding: utf-8 -*-
# 什么是面向对象
#需求
# - 老妈的交通工具有两个,电动车和自行车
# - 家里离菜场共 20 公里
# - 周一的时候骑电动车去买菜,骑了 0.5 小时
# - 周二的时候骑自行车去卖菜,骑了 2 小时
# - 周三的时候骑电动车去卖菜,骑了 0.6 小时
# - 分别输出三天骑行的平均速度
# def main():
# distance = 20
# e_bicycle = '电动车'
# bicycle = '自行车'
# day1 = '周一'
# hour1 = 0.5
# speed1 = 20/h... |
998,972 | 0fc31f8a113790c331c24eb97077f6701610d398 | """Handles the data."""
import os
TRANSCRIPTION_PATH = './ground-truth/transcription.txt'
KEYWORDS = "task/keywords_train.txt"
KEYWORDS_TEST = "task/keywords.txt"
IMG_PATH = "Cropped-images/"
def get_train_sample(keyword):
"""Gets a train image that matches the keyword."""
file = open(TRANSCRIPTION_PATH, 'r'... |
998,973 | fd4466d675b2f205a5ddc7c7a269298d119264b0 | import csv
import matplotlib.pyplot as plt
class Plotter(object):
def add_figure(self, title, x_label, y_label):
figure = plt.figure()
plt.grid()
plt.title(title)
plt.xlabel(x_label)
plt.ylabel(y_label)
return figure.number
def add_line(self, data, label, figu... |
998,974 | 9066016aa8973ea3cbb063309fafa2d9eee91886 | from pathlib import Path
from kaybee.app import kb
from kaybee.plugins.articles.base_article_reference import BaseArticleReference
@kb.resource('author')
class Author(BaseArticleReference):
def headshot_thumbnail(self, usage):
docpath = Path(self.docname)
parent = docpath.parent
prop = se... |
998,975 | 95612b9b755bc53de4d191717ae9011cf8404ca6 | from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
app_name = 'cuentas'
urlpatterns = [
path('user/current/', views.CurrentUser.as_view(), name='current'),
path('users/', views.UserList.as_view(), name='list'),
# path('user/create/', views.User... |
998,976 | 0e4fb47ab5738494e6839c36ce05af1d2586adfe | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created by Cphayim at 2018/06/18
"""
# def fact(n):
# if n <= 1:
# return n
# return n * fact(n - 1)
# print(fact(5))
# for x in ran5
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for x in range(0, len(a), 2):
print(a[x], end=' | ')
b = a[0:len(a):2]
print... |
998,977 | 94b1acc93c757cd4cd1ccf88e8c142eebc578239 | from zen.ui import _readchar, _read_action, read_until_action, Action
def test_getting_single_char() -> None:
assert _readchar(_testing="a")=="a"
def test_control_c_raises_keyboard_interrupt() -> None:
try:
_readchar(_testing="\x03")
except KeyboardInterrupt:
return None
assert False
... |
998,978 | 4c199f254491e8d46609c696d67809cddccd2a30 | import yaml
import constants
class YamlConfigError(KeyError):
pass
def validate_queue_config(directive, queue_config):
try:
queue_url = queue_config['url']
except KeyError:
raise YamlConfigError(
f"{directive} queue is type 'sqs', but queue 'url' not provided"
)
... |
998,979 | 11c93d8d072b1298b3c1c90cd7f444d010f5c9dd | def key(ll):
return "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d" % (ll[0],ll[1],ll[2],ll[3],ll[4],ll[5],ll[6],ll[7],ll[8],ll[9])
max = 10000
lst = {}
for i in range(max):
j = i*i*i
l = [0]*10
while(j > 0):
l[j%10] += 1
j /= 10
k = key(l)
if(not(k in lst)):
lst[k] = []
lst[k].append(i)
min = max
for i in lst:
if(le... |
998,980 | 7ab69e8233ebf0946a62b66a1d1ccfc3a891599e | #! python
# Problem # : 158B
# Created on : 2019-01-14 22:25:35
def Main():
n = int(input())
t = 0
arr = [int(x) for x in input().split(' ')]
arr.sort()
i = 0
j = len(arr) - 1
k = 0
m = 4
while j >= i:
if i is j:
k += 1
break
while a... |
998,981 | ef27768b66fab231818287d7b231fbbe98ab1ea4 | #!/usr/bin/env python3
#coding = utf-8
import bisect
# the module for inserting and sorting operations on ordered arrays.
# bisect.bisect_left(list, value)
# find the location where the value will be inserted but not inserted.
# returns the position to the left of x if x exists in list.
def money(n, m, limit, maxm):... |
998,982 | 10dcf7f7ddab150676ceb860494abd4b6d0838a3 | import pathlib
import sys
from collections import defaultdict
import argparse
import numpy as np
import torch
from torch.utils.data import DataLoader
from dataset_1 import SliceDataDev
from torch.nn import functional as F
from models import DnCn
import h5py
from tqdm import tqdm
from collections import OrderedDict
impo... |
998,983 | f6be74af798951ffedc5813b26c0d7ef159483c9 | import numpy as np
import gridWorld
import helper
class MonteCarlo():
def __init__(self, dimensions=(4, 5)):
self.gw = gridWorld.Grid()
self.dimensions = dimensions
self.gw.init_sample_grid_world(dimensions)
self.q = np.zeros(shape=(dimensions[0], dimensions[1], 4))
self.re... |
998,984 | d8ca98998ac7abb79d26f2778ac22f547ec4fe6c | # 20P
# Create a dictionary that contains the result functions as keys and as values the list of results from calling that
# function with x in range -10, 10 as value
def build(a, b, c):
def response(x):
result = 0
result = a * x ** 2 + b * x + c
return result
return response
list_of_... |
998,985 | 4849e761943dbbd5f94f192494c52d26643221bf | #! -*- coding=utf-8 -*-
import inspect
class Friends:
def __init__(self, name = None, grade = None, age = None):
self.name = name
self.grade = grade
self.age = age
def __str__(self):
return 'Friends: name=%s, grade=%s, grade=%s'% (self.name, self.grade, self.age)
def test(... |
998,986 | 4c22b412cf420665c631832834a9d29bba621c08 | import re
# Defines the constant names used when resolving the commands type.
commands = {
'arithmetic': ['add', 'sub', 'neg', 'eq', 'gt', 'lt', 'and', 'or', 'not'],
'push': 'C_PUSH',
'pop': 'C_POP',
'label': 'C_LABEL',
'goto': 'C_GOTO',
'if-goto': 'C_IF',
'function': 'C_FUNCTION',
'cal... |
998,987 | 8a950f5ff6bd1d92cfd9da0103086f0f16b58526 |
def report(xs):
result=""
total=0
countscore=0
i=0
while i < len(xs):
count=0
names=[]
if isinstance(xs[i], int):
total=total+xs[i]
countscore=countscore+1
i=i+1
if i==len(xs):
break
while isinstance(xs[i], str)... |
998,988 | f385f9d901ae3a757d352cddc14da6522f522233 | import discord
import config
import asyncio
import time
from datetime import datetime, timedelta
import pytz
import logging
import random
from managers.CommandsManager import CommandsManager
from managers.DatabaseManager import DatabaseManager
from managers.StatisticsManager import StatisticsManager
from managers.Teamu... |
998,989 | c0afff62c00035a2cc7e76f9639526136de9a4c3 | import tables
import scipy
import sys
sys.path.append("../system/")
sys.path.append("../lifting/")
sys.path.append("../restriction/")
sys.path.append("..")
sys.path.append("../..")
sys.path.append("../../..")
import Point.Point as Point
import Solver.NewtonSolver as NewtonSolver
import Solver.GMRESLinearSolver as GMR... |
998,990 | 69eb4bf441fa935426db03eda7cb237599328b94 | import pygame, sys
import simpy
pygame.init()
(width, height) = (640, 480)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Bird Simulation")
screen.init()
pygame.display.flip()
print("Hello World")
while True:
for event in pygame.event.get():
if event.typ... |
998,991 | bdec0becb56d71ba921f1495e9e2620ff5950c31 | __author__ = 'zhengqin'
class Solution(object):
"""
Question: Write a function, that given two sorted lists of integers as input,
returns a single sorted list with items from both lists with no duplicate elements.
Example:
input: a = {1,2,3}; b = {4,5,6}; output: c = {1,2,3,4,5,6};
input: a =... |
998,992 | 39726118bd471231a2cac95f0e15d308212839dc | # Write a function which takes two strings and checks whether the characters in the first string form a subsequence of the characters in the second string. The characters in the first should appear without their order changing in the second string.
def forms_subsequence(str1, str2):
result = ""
str1_obj = {}
... |
998,993 | ab67e4865beca24295be5b7d68b6bbeaa8aebb34 | class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
# Three conditions:
# 1. num has to be positive
# 2. num has to contain only one '1' bit (not num&(num-1))
# 3. num's single '1' bit has to be the ones in 0x55555... |
998,994 | 4557416a6374c67480b79993c2740b690a9a7250 | # Hugo Colenbrander 27-07-2020
# Given: Three positive integers k, m, and n,
# representing a population containing k+m+n organisms:
# k individuals are homozygous dominant for a factor,
# m are heterozygous, and n are homozygous recessive.
# Return: The probability that two randomly selected mating organisms will
# p... |
998,995 | c6834feceb556fa08927d171f25e1168f4ae1e0e | from django.shortcuts import render, get_list_or_404, get_object_or_404
from .models import *
from django.utils import timezone
from datetime import datetime, timedelta, date
# Create your views here.\
def index(request):
footer = Footer.objects.all()[0]
recruiting_banner = RecruitingBanner.objects.all()[0]
... |
998,996 | 3923a78f91b773528b51d013c5a9823b8c55f9ce | from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('introduction', views.introductionview, name='introduction'),
path('faq',views.faqview , name='faq'),
path('product',views.productview, name='product'),
] |
998,997 | 05762a0e7189632d17138e054680a6d522ea6e63 | #!/usr/local/bin/python3
import time
import logging
import logging.handlers
import datetime
import pymysql
import traceback
class BaikalDBClient:
def __init__(self, host = '',user = '',passwd = '',db = '',port = 3306,charset = 'utf8'):
self.host = host
self.user = user
self.passwd = passwd... |
998,998 | fb2822c737732bb309bce1cada5770cc5031990d | class Node(object):
def __init__(self: 'Node', value: object) -> None:
self._value = value
self.next = None
def get_value(self: 'Node') -> object:
return self._value
class Queue(object):
'''An implementation of the queue abstract data type.'''
def __init__(self: 'Queue... |
998,999 | c19da4698c630e0f8c89e69f2108ae3123428636 | __author__ = 'micanzhang'
import web
from app.routes import urls
from app.model import DBSession
from app.helper import load_sqla, orm, SQLAStore
# web.py application instance
app = web.application(urls, globals())
app.add_processor(load_sqla)
web.ctx.orm = orm()
if web.config.get('_session') is None:
web.config... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.