index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
7,800
63f155f7da958e9b6865007c701f7cf986b0cbac
# -*- coding: utf-8 -*- """ Created on Tue Mar 24 12:16:15 2020 @author: zhangjuefei """ import sys sys.path.append('../..') import numpy as np from sklearn.datasets import fetch_openml from sklearn.preprocessing import OneHotEncoder import matrixslow as ms # 加载MNIST数据集,取一部分样本并归一化 X, y = fetch_openml('mnist_784', v...
7,801
881afd6877508243fa5056d2a82d88ba69ffb8c0
from graphviz import Digraph from math import log2, ceil def hue_to_rgb(p, q, t): if t < 0: t += 1 if t > 1: t -= 1 if t < 1/6: return p + (q - p) * 6 * t if t < 1/2: return q if t < 2/3: return p + (q - p) * (2/3 - t) * 6 return p def hsl_to_rgb(h, s, l): h /= 360 q = l * (1 + s) if l...
7,802
a5dff32dfbe93ba081144944381b96940da541ad
# Generated by Django 2.0.5 on 2019-06-12 08:03 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('doctor', '0257_merge_20190524_1533'), ('doctor', '0260_merge_20190604_1428'), ] operations = [ ]
7,803
9cfbb06df4bc286ff56983d6e843b33e4da6ccf8
""" Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). Example 1: Input: root = [1, 2, 2, 3, 4, 4, 3] Output: true 1 / \ 2 2 / \ / \ 3 4 4 3 Example 2: Input: root = [1, 2, 2, None, 3, None, 3] Output: false 1 / ...
7,804
b63dc8b9aa2f0593a4a7eb52a722a9c4da6c9e08
import pandas as pd from pandas import Series, DataFrame def load_excel( data_path, data_name, episode_Num): data_name = data_name + str(episode_Num)+'.xlsx' dataframe = pd.read_excel(data_path + data_name,index_col=0) return dataframe def dataframe_to_numpy(dataframe): numpy_array = dataframe.to_nump...
7,805
8a1f024be00200218782c919b21161bf48fc817e
# from django.contrib.auth.models import User from django.db.models.signals import post_save from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models # from applications.models import ApplicationReview # from profiles.models import Restaurant, Program, Courier # Enum f...
7,806
c967aa647a97b17c9a7493559b9a1577dd95263a
# -*- coding: utf-8 -*- import math # 冒泡排序(Bubble Sort) # 比较相邻的元素。如果第一个比第二个大,就交换它们两个; # 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对,这样在最后的元素应该会是最大的数; # 针对所有的元素重复以上的步骤,除了最后一个; # 重复步骤1~3,直到排序完成。 # 冒泡排序总的平均时间复杂度为:O(n^2) def bubble_sort(input): print("\nBubble Sort") input_len = len(input) print("length of input: %d" % i...
7,807
bef16443f77b2c1e09db9950a4617703085d9f71
import datetime import numpy as np import tensorflow as tf from alphai_time_series.performance_trials.performance import Metrics import alphai_cromulon_oracle.cromulon.evaluate as crocubot_eval import alphai_cromulon_oracle.cromulon.train as crocubot_train from alphai_cromulon_oracle.cromulon.helpers import Tensorfl...
7,808
8bc465a1b546907d8a9e5eee2cae672befb1ea13
n = int(input()) b = 0 p = [0,0] flg = True for i in range(n): t,x,y = map(int,input().split()) diff = abs(x - p[0]) + abs(y - p[1]) time = t - b if(diff > time or time%2 != diff %2): flg = False break else: b = t p[0] = x p[1] = y if flg: print("Yes") else: print("No")
7,809
f9d8280d765826b05bfa7989645e487431799f85
from flask import Flask from flask_script import Manager app = Flask(__name__) manager = Manager(app) @app.route('/') def index(): return '2018/6/1 hello python' @app.route('/news') def news(): return '内蒙古新闻资讯,请选择浏览' if __name__ == '__main__': manager.run()
7,810
f73a316b6020908472e35a7b78959a9bda6e8e56
# 导包 from time import sleep from selenium import webdriver # 实例化浏览器 driver = webdriver.Firefox() # 打开页面 driver.get(r"F:\BaiduYunDownload\webdriverspace\sources\注册实例.html") driver.maximize_window() sleep(2) # 定位注册A按钮并点击 driver.find_element_by_link_text("注册A网页").click() # 获取当前敞口句柄 current_handle = driver.current_windo...
7,811
0547751af7bbac42351476dde591d13d40fb37eb
#!/usr/bin/env python """ Otsu method for automatic estimation of $T$ threshold value - assumes two maxima of grayscale histogram & searches for optimal separation Parameters Usage Example $ python <scriptname>.py --image ../img/<filename>.png ## Explain """ import numpy as np import argparse import mahota...
7,812
03284f20e614a5f8f5c21939acf49490d6ffd3a3
import json startTime = "" endTime = "" controller = 0 for files in range(30): file = open("NewResults" + str(files+1) + ".data") for line in file: if line != "\n": j = json.loads(line) if controller == 0: startTime = j['metrics'][0]['startTime'] helper = startTime.split(" ") hour = helper[1].sp...
7,813
a1b0e72b62abc89d5292f199ec5b6193b544e271
DEBUG = True SQLALCHEMY_DATABASE_URI = "postgresql://username:password@IPOrDomain/databasename" SQLALCHEMY_TRACK_MODIFICATIONS = True DATABASE_CONNECT_OPTIONS = {} THREADS_PER_PAGE = 2
7,814
1c685514f53a320226402a4e4d8f3b3187fad615
import uuid from datetime import date import os import humanize class Context: def __init__(self, function_name, function_version): self.function_name = function_name self.function_version = function_version self.invoked_function_arn = "arn:aws:lambda:eu-north-1:000000000000:function:{}".f...
7,815
cdbc7d703da69adaef593e6a505be25d78beb7ce
import numpy as np class EdgeListError(ValueError): pass def check_edge_list(src_nodes, dst_nodes, edge_weights): """Checks that the input edge list is valid.""" if len(src_nodes) != len(dst_nodes): raise EdgeListError("src_nodes and dst_nodes must be of same length.") if edge_weights is N...
7,816
4c5b3042a785342d6ef06fdc882e0dcf91a787c3
from datetime import date import config import datetime import numpy import pandas import data_sources from data_sources import POPULATION, convert_to_ccaa_iso import material_line_chart import ministry_datasources HEADER = '''<html> <head> <title>{}</title> <script type="text/javascript" src="https://w...
7,817
907f0564d574f197c25b05a79569a8b6f260a8cd
import math from os.path import join, relpath, dirname from typing import List, Tuple from common import read_input convert_output = List[str] class GridWalker: def __init__(self): self._current_pos = [0, 0] self._heading = math.pi / 2 @property def position(self): return self....
7,818
5b7567129d447ae2b75f4a8f9c26127f8b7553ec
#app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' #app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True; #db = SQLAlchemy(app) # MONGODB CREATION #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] print("Database created........") #Verif...
7,819
772e2e0a442c1b63330e9b526b76d767646b0c7c
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QGraphicsOpacityEffect, \ QPushButton from PyQt5.QtCore import Qt class ToolBar(QWidget): """ Window for entering parameters """ def __init__(self, parent): super().__init__(parent) self._main_wnd = parent self.setAttribut...
7,820
243794d36a1c6861c2c3308fe6a52ec19b73df72
"""Activate coverage at python startup if appropriate. The python site initialisation will ensure that anything we import will be removed and not visible at the end of python startup. However we minimise all work by putting these init actions in this separate module and only importing what is needed when needed. For...
7,821
d47ea763ac1a4981fc5dee67cd396ad49570f923
#coding=utf-8 from numpy import * #代码5-1,Logistic回归梯度上升优化算法。 def loadDataSet(): """解析文件 Return: dataMat 文档列表 [[1,x1,x2]...]; labelMat 类别标签列表[1,0,1...] @author:VPrincekin """ dataMat = []; labelMat= [] fr = open('testSet.txt') #每行前两个分别是X1和X2,第三个只是数据对应的类别 for line in fr.readlines(): ...
7,822
e0fbb5ad6d822230865e34c1216b355f700e5cec
from bisect import bisect_left as bisect while True: xp, yp = set(), set() veneer = [] W, H = map(int, input().split()) if not W: break N = int(input()) for i in range(N): x1, y1, x2, y2 = map(int, input().split()) veneer.append((x1, y1, x2, y2)) xp.add(x1) ...
7,823
34009d1aa145f4f5c55d0c5f5945c3793fbc6429
with open('vocabulary.txt', 'r') as f: for line in f: information = line.strip().split(': ') # print(information[0], information[1]) question = information[1] answer = information[0] my_answer = input(f'{question}:') if my_answer == answer: print('맞았습니다!'...
7,824
b1a6593e7b528238e7be5ea6da4d1bfee0d78067
import serial import mysql.connector ser = serial.Serial('/dev/serial0', 9600) while True: data = ser.readline() if data[0]==";": print(data) data = data.split(";") if data[1] == "1": fonction = data[1] add = data[2] tmp = data[3] debit = data[4] ser.write([123]) #test affichage print "Sa...
7,825
0509afdce0d28cc04f4452472881fe9c5e4fbcc4
from rest_framework import serializers from .models import * class MovieSerializer(serializers.Serializer): movie_name = serializers.ListField(child=serializers.CharField()) class FilmSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = '__all__'
7,826
c02f46e8d89dd4b141c86df461ecbb8ed608b61b
#!/usr/bin/python import gzip import os infiles = [] ids=[] ages=[] with open('all_C_metadata.txt') as f: f.readline() f.readline() for line in f: infiles.append(line.split('\t')[0]) ids.append(line.split('\t')[1]) ages.append(line.split('\t')[2]) with open('all_C_samples/diversi...
7,827
bf98e81c160d13b79ebe9d6f0487b57ad64d1322
""" Author: Le Bui Ngoc Khang Date: 12/07/1997 Program: Write a script that inputs a line of plaintext and a distance value and outputs an encrypted text using a Caesar cipher. The script should work for any printable characters. Solution: Enter a message: hello world Enter distance value: 3 khoor#zruog """ # Reque...
7,828
b164dc8183c0dc460aa20883553fc73acd1e45ec
def count_singlekey(inputDict, keyword): # sample input # inputDict = { # abName1: { dna: 'atgc', protein: 'x' } # abName2: { dna: 'ctga', protein: 'y' } # } countDict = {} for abName, abInfo in inputDict.iteritems(): if countDict.has_key(abInfo[keyword]): countDict[abInfo[keyword]...
7,829
f6e0215f9992ceab51887aab6a19f58a5d013eb4
from ad_api.base import Client, sp_endpoint, fill_query_params, ApiResponse class CampaignNegativeKeywords(Client): @sp_endpoint('/v2/sp/campaignNegativeKeywords/{}', method='GET') def get_campaign_negative_keyword(self, keywordId, **kwargs) -> ApiResponse: r""" get_campaign_negative_keyword(...
7,830
d99fd3dc63f6a40dde5a6230111b9f3598d3c5fd
from torchvision import datasets, transforms import torch def load_data(data_folder, batch_size, train, num_workers=0, **kwargs): transform = { 'train': transforms.Compose( [transforms.Resize([256, 256]), transforms.RandomCrop(224), transforms.RandomHorizontalFli...
7,831
04822e735c9c27f0e0fcc9727bcc38d2da84dee6
import logging from django.contrib.auth import get_user_model from django.db import models from rest_framework import serializers from rest_framework.test import APITestCase from ..autodocs.docs import ApiDocumentation from .utils import Deferred log = logging.getLogger(__name__) def get_serializer(endpoint, met...
7,832
e15ea7d167aad470d0a2d95a8a328b35181e4dc3
############################################################################## # Copyright by The HDF Group. # # All rights reserved. # # # # Th...
7,833
4ecd756b94b0cbab47a8072e9bccf26e2dd716d0
import pytest import numpy as np from GSPA_DMC import SymmetrizeWfn as symm def test_swap(): cds = np.load('h3o_data/ffinal_h3o.npy') dws = np.load('h3o_data/ffinal_h3o_dw.npy') cds = cds[:10] a = symm.swap_two_atoms(cds, dws, atm_1=1,atm_2=2) b = symm.swap_group(cds, dws, atm_list_1=[0,1],atm_lis...
7,834
d218b72d1992a30ad07a1edca1caf04b7b1985f6
from introduction import give_speech from staring import stare_at_people from dow_jones import visualize_dow_jones from art_critic import give_art_critiques from hipster import try_hipster_social_interaction from empathy import share_feelings_with_everyone from slapstick import perform_slapstick_humor from ending impor...
7,835
7edd833103e1de92e57559c8a75379c26266963b
# -*- encoding: utf-8 -*- from openerp.tests.common import TransactionCase from openerp.exceptions import ValidationError class GlobalTestOpenAcademySession(TransactionCase): ''' Global Test to openacademy session model. Test create session and trigger constraint ''' # Pseudo-constructor methods...
7,836
94e9e7c4c09c8c4de4c8f2649707a949d5f5f856
from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models import Max from django.core.validators import RegexValidator from django.utils import timezone class User(AbstractUser): is_developer = models.BooleanField('developer status', default=False) is_marketing = mo...
7,837
8c055816def1c0a19e672ab4386f9b9a345b6323
#!/usr/bin/env python # -*- coding: utf-8 -*- import cProfile import re import pstats import os import functools # cProfile.run('re.compile("foo|bar")') def do_cprofile(filename): """ decorator for function profiling :param filename: :return: """ def wrapper(func): @functools.wraps...
7,838
9f31694d80f2dcc50a76b32aa296871694d3644d
from machine import Pin, PWM import time # externe LED zit op pin D1 (GPIO5) PinNum = 5 # pwm initialisatie pwm1 = PWM(Pin(PinNum)) pwm1.freq(60) pwm1.duty(0) step = 100 for i in range(10): # oplichten while step < 1000: pwm1.duty(step) time.sleep_ms(500) step+=100 # uitdoven ...
7,839
dd95d14f35b6a92b3363d99a616678da18733a61
import os import redis class Carteiro(): if os.environ.get("REDIS_URL") != None: redis_pool = redis.ConnectionPool.from_url(os.environ.get("REDIS_URL")) else: redis_pool = '' def __init__(self, id, pacote): if os.environ.get("REDIS_URL") != None: self.redis_bd ...
7,840
3fe98c865632c75c0ba0e1357379590f072bf662
../pyline/pyline.py
7,841
44d9e628e31cdb36088b969da2f6e9af1b1d3efe
from collections import Counter from copy import deepcopy from itertools import count from traceback import print_exc #https://www.websudoku.com/?level=4 class SudukoBoard: side=3 sz=side*side class Cell: def __init__(self,board,row,col): self._values= [None] * SudukoBoard.sz ...
7,842
5bd2cf2ae68708d2b1dbbe0323a5f83837f7b564
import requests from urllib.parse import urlparse, urlencode from json import JSONDecodeError from requests.exceptions import HTTPError def validate_response(response): """ raise exception if error response occurred """ r = response try: r.raise_for_status() except HTTPError as e: ...
7,843
15a894e6f94fc62b97d1614a4213f21331ef12a0
import collections s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] d = collections.defaultdict(list) d2 = {'test':121} for k, v in s: d[k].append(v) d['test'].append('value') print list(d.items()) print d print d['blue'] print type(d) print type(d2)
7,844
de88e2d2cf165b35f247ea89300c91b3c8c07fea
# Copyright (c) 2023 Intel Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writ...
7,845
15c1db535beb115c45aeba433a946255f70fa86e
# -*- coding: utf-8 -*- import base64 import logging from decimal import Decimal import requests from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from currencies.currencies import decimal_round from payments.systems import base from payments.systems.ban...
7,846
44b6ee8488869da447882457897ce87b2fdea726
import getpass print('****************************') print('***** Caixa Eletronico *****') print('****************************') account_typed = input("Digite sua conta: ") password_typed = getpass.getpass("Digite sua senha: ")
7,847
89ce3d3ec9691ab8f54cc0d9d008e06c65b5f2cc
#grabbed the following from moses marsh -- https://github.com/sidetrackedmind/gimme-bus/blob/master/gimmebus/utilities.py from datetime import datetime as dt from math import radians, cos, sin, acos, asin, sqrt import networkx as nx ## These functions will go in model.py for matching historical GPS ## positions to th...
7,848
c48d5d9e088acfed0c59e99d3227c25689d205c6
naam = raw_input("Wat is je naam?") getal = raw_input("Geef me een getal?") if naam == "Barrie": print "Welkom " * int(getal) else: print "Helaas, tot ziens"
7,849
29c25721a4754650f0d5d63d6cc3215cb0ea1b3e
""" bubble sort start at beginning switch to left if smaller - very naive approach n-1 comparisons, n-1 iterations (n-1)^2 worst case: O(n^2) = average case best case: O(n) space complexity: O(1) """ def bubbleSort(list): for num in range(len(list)-1,0,-1): for i in range(num): if list[i] > list...
7,850
1a1a217b382f3c58c6c4cd3c1c3f556ae945f5a7
from selenium import webdriver; from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support.select import Select from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome(Chr...
7,851
22e24e8dd49367ae57d1980c4addf48d65c5e897
''' Created on Nov 20, 2012 @author: shriram ''' import xml.etree.ElementTree as ET from xml.sax.saxutils import escape ''' Annotating only Sparse and Non Sparse Lines ''' class Trainer: def html_escape(self,text): html_escape_table = { '"': "&quot;", "'": "&apos;" } re...
7,852
f3a3746c48617754aad5ae8d0d7a0b8908c34562
# coding: utf-8 # In[5]: import os import numpy as np import pandas as pd from PIL import Image import argparse import time import shutil from sklearn.metrics import accuracy_score, mean_squared_error import torch import torch.optim from torch.utils.data import Dataset, DataLoader from torch.autograd import Variab...
7,853
bacd0c729193f064b21ab8e01e98dfc276094458
# -*- coding: utf-8 -*- # # Copyright (C) 2011 Taobao .Inc # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://code.taobao.org/license.html. # # This software consists of voluntary ...
7,854
c3719f30bcf13061134b34b0925dfa2af4535f14
#!/usr/bin/env python from setuptools import setup import NagAconda setup(name=NagAconda.__name__, version=NagAconda.__version__, description="NagAconda is a Python Nagios wrapper.", long_description=open('README').read(), author='Steven Schlegel', author_email='steven@schlegel.tech', ...
7,855
d205c38e18b1acf8043a5976a90939b14358dc40
#-*- coding: utf-8 -*- espacos = ["__1__", "__2__", "__3__", "__4__"] facil_respostas=["ouro","leao","capsula do poder","relampago de plasma"] media_respostas=["Ares","Saga","Gemeos","Athena"] dificil_respostas=["Shion","Aries","Saga","Gemeos"] def inicio_game(): apresentacao=raw_input("Bem vindo ao qui...
7,856
2d5abcd75dcbeb1baa3f387035bdcc3b7adbfe3f
''' 8-6. 도시 이름 도시와 국가 이름을 받는 city_country() 함수를 만드세요. 이 함수는 다음과 같은 문자열을 반환해야 합니다. 'Santiago, Chile' - 최소한 세 개의 도시-국가 쌍으로 함수를 호출하고 반환값을 출력하세요. Output: santiago, chile ushuaia, argentina longyearbyen, svalbard '''
7,857
f715628da2f1b950b8fbf8aa5b033e5299d3e224
lc_headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15", "authority": "leetcode.com", } lc_all = "https://leetcode.com/api/problems/all/" lc_submissions = "https://leetcode.com/api/submissions/?off...
7,858
fe5398b03d2f0cfc7c972677faa0ea3ec701469e
# Create your models here. from django.db import models from django.utils import timezone from django.db import models # Create your models here. #필드 개수가 다르다. class Post(models.Model): #이 Post의 저자이다라는 의미, CASCADE : 종속이라는 의미 author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.C...
7,859
62de629d8f28435ea8dc3dc093cac95e7cedf128
# 6. Evaluate Classifier: you can use any metric you choose for this assignment # (accuracy is the easiest one). Feel free to evaluate it on the same data you # built the model on (this is not a good idea in general but for this assignment, # it is fine). We haven't covered models and evaluation yet, so don't worry ...
7,860
90e475dfd128689dd4e1a5375ced6e4cbfb73c07
import sys N = int(input()) card = [int(x+1) for x in range(N)] trash = [] while len(card)>1: topCard = card.pop(0) trash.append(topCard) card.append(card.pop(0)) outputStr = "" for i in range(len(trash)): outputStr += str(trash[i]) + " " outputStr += str(card[0]) print(outputStr)
7,861
4da1a97c2144c9aaf96e5fe6508f8b4532b082d4
import tweepy import time import twitter_credentials as TC auth = tweepy.OAuthHandler(TC.CONSUMER_KEY, TC.CONSUMER_SECRET) auth.set_access_token(TC.ACCESS_TOKEN, TC.ACCESS_TOKEN_SECRET) api = tweepy.API(auth) count = 1 # Query to get 50 tweets with either Indiana or Weather in them for tweet in tweepy.Cursor(api.sea...
7,862
db36c82717aa0bacffce7a3e2724ed2bb586c7fb
from solution import find_days import pudb def test(): T = [1, 2, 3, 1, 0, 4] # pudb.set_trace() res = find_days(T) assert res == [1, 1, 3, 2, 1, 0]
7,863
3a6eaa238e78e7a818bcf6e18cc7881eadf94b07
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------- # Name: sfp_googlesearch # Purpose: Searches Google for content related to the domain in question. # # Author: Steve Micallef <steve@binarypool.com> # # Created: 07/05/2012 # Copyright...
7,864
9aaaa744780dbd32b14e09a34976a2a0a3ce34f7
from packages import data as DATA from packages import plot as PLOT from packages import universal as UNIVERSAL from packages import currency_pair as CP import matplotlib.pyplot as plt import mpl_finance as mpf from packages import db as DB import CONSTANTS import datetime from matplotlib.pylab import date2num from mat...
7,865
5e1398ed628917a42cc465e7cc2979601f0f4fbc
#!/usr/bin/env python #**************************************************************************** # fieldformat.py, provides non-GUI base classes for field formating # # TreeLine, an information storage program # Copyright (C) 2006, Douglas W. Bell # # This is free software; you can redistribute it and/or modify it ...
7,866
3ffcab4b36c6ca05f1e667c628ebb873ebdc0d25
# -*- coding: utf-8 -*- import serial import time import argparse def write_command(serial, comm, verbose = False, dt = None): """ Encodes a command and sends it over the serial port """ if verbose and comm != "": if dt is None: print("{} \t\t-> {}".format(comm, serial.port...
7,867
f29ad02f3781c7a7d2a1f0c97626dd5c7ea2417e
""" CP1404 Practical unreliable car test """ from unreliable_car import UnreliableCar def main(): good_car = UnreliableCar("good car", 100, 80) bad_car = UnreliableCar("bad car", 100, 10) for i in range(10): print("try to drive {} km".format(i)) print("{:10} drove {:2}km".format(good_car....
7,868
656927013d9a0254e2bc4cdf05b7cfd5947feb05
from .proxies import Proxies from .roles import Roles from .products import Products from .resourcefiles import ResourceFiles class Apigee(object): """Provides easy access to all endpoint classes Args: domain (str): Your Auth0 domain, e.g: 'username.auth0.com' token (str): Management API v2...
7,869
b459919e779063247c176e127368c687c903cf0f
from checkio.home.long_repeat import long_repeat def test_long_repeat(): assert long_repeat("sdsffffse") == 4, "First" assert long_repeat("ddvvrwwwrggg") == 3, "Second" def test_fails_1(): assert long_repeat("") == 0, "Empty String" def test_fails_2(): assert long_repeat("aa") == 2
7,870
f546eb40ee8a7308ded62532731561029e5ec335
import requests import os from slugify import slugify as PipSlugify import shutil # will install any valid .deb package def install_debian_package_binary(package_path): os.system("sudo dpkg -i {package_path}".format( package_path=package_path )) os.system("sudo apt-get install -f") def download_inst...
7,871
57c911c9a10f9d116f1b7099c5202377e16050f1
from typing import * class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: cells = {} for i in range(9): for j in range(9): if board[i][j] != ".": val = board[i][j] # is unique in r...
7,872
85f5f9370896eac17dc72bbbf8d2dd1d7adc3a5b
""" """ import cPickle as pickle def convert_cpu_stats_to_num_array(cpuStats): """ Given a list of statistics (tuples[timestamp, total_cpu, kernel_cpu, vm, rss]) Return five numarrays """ print "Converting cpus stats into numpy array" c0 = [] c1 = [] c2 = [] c3 = [] c4 = [] ...
7,873
63a9060e9933cc37b7039833be5f071cc7bf45bf
#import getCanditatemap() from E_18_hacksub import operator, pdb, collections, string ETAOIN = """ etaoinsrhldcumgyfpwb.,vk0-'x)(1j2:q"/5!?z346879%[]*=+|_;\>$#^&@<~{}`""" #order taken from https://mdickens.me/typing/theory-of-letter-frequency.html, with space added at the start, 69 characters overall length = 128 #ETA...
7,874
e766bba4dec0d37858f1f24083c238763d694109
from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency as c, currency_range ) import random import itertools doc = """ Public good game section (Rounds and feedback). """ class Constants(BaseConstants): name_in_url = 'public_goods' players...
7,875
5ee1d8ef7ec4b191e0789ceb9c6dd2d58af526a0
# -*- coding: utf-8 -*- import pytest from bravado.client import ResourceDecorator from bravado.client import SwaggerClient def test_resource_exists(petstore_client): assert type(petstore_client.pet) == ResourceDecorator def test_resource_not_found(petstore_client): with pytest.raises(AttributeError) as ex...
7,876
07b6ded9b4841bdba62d481664a399f0b125fcbf
import pandas as pd; import time; import matplotlib.pyplot as plt; import matplotlib.cm as cm import matplotlib.patches as mpatch; import numpy as np; import sys; sys.path.append("/uufs/chpc.utah.edu/common/home/u0403692/prog/prism/test") import bettersankey as bsk; datapath = "/uufs/chpc.utah.edu/common/home/u04036...
7,877
df518fd719b7eafffd8fee92c926d4d24b65ce18
import os import json import pathlib from gql import gql, Client from gql.transport.aiohttp import AIOHTTPTransport # Select your transport with a defined url endpoint transport = AIOHTTPTransport(url="https://public-api.nbatopshot.com/graphql") # Create a GraphQL client using the defined transport client = Client(tr...
7,878
ccc2a976d06e2fa6c91b25c4f95a8f0da32e9b5e
""" Author: Yudong Qiu Functions for solving unrestricted Hartree-Fock """ import numpy as np from qc_python import basis_integrals from qc_python.common import chemical_elements, calc_nuclear_repulsion def solve_unrestricted_hartree_fock(elems, coords, basis_set, charge=0, spinmult=1, maxiter=150, enable_DIIS=True...
7,879
0ceb9eac46e3182821e65a1ae3a69d842db51e62
STATUS_DISCONNECT = 0 STATUS_CONNECTED = 1 STATUS_OPEN_CH_REQUEST = 2 STATUS_OPENED = 3 STATUS_EXITING = 4 STATUS_EXITTED = 5 CONTENT_TYPE_IMAGE = 0 CONTENT_TYPE_VIDEO = 1 STATUS_OK = 0 STATUS_ERROR = 1 class Point(object): def __init__(self, x = 0, y = 0): self.x = x self.y = y class ObjectDe...
7,880
f7283750923e1e430ff1f648878bbb9a0c73d2c4
from settings import * helpMessage = ''' **Vocal / Musique** `{0}join` Va rejoindre le salon vocale dans laquelle vous êtes. `{0}leave` Va partir du salon vocale dans laquelle vous êtes. `{0}play [YouTube Url]` *ou* `{0}play [musique ou video à rechercher]` Commencera à jouer l'audio de la vidéo / chans...
7,881
5e14eeaa3c79bfdd564f3bfd1575c9bbf1a3773d
"""Command generator for running a script against a BigQuery cluster. Contains the method to compile the BigQuery specific script execution command based on generic arguments (sql script, output destination) and BigQuery specific arguments (flag values). """ __author__ = 'p3rf@google.com' from absl import flags fla...
7,882
e877f16e604682488d85142174ce4f3f6cee3f18
from sys import argv from pyspark import SparkContext import json import re import math from _datetime import datetime start_time = datetime.now() input_file = argv[1] model_file = argv[2] stopwords = argv[3] sc = SparkContext(appName='inf553') lines = sc.textFile(input_file).map(lambda x: json.loads(x)) stopwords = sc...
7,883
b849a2902c8596daa2c6da4de7b9d1c07b34d136
# Generate some object patterns as save as JSON format import json import math import random from obstacle import * def main(map): obs = [] for x in range(1,35): obs.append(Obstacle(random.randint(0,map.getHeight()), y=random.randint(0,map.getWidth()), radius=20).toJsonObject()) jsonOb={'map': {'obstacle': obs}}...
7,884
b9a75f4e106efade3a1ebdcfe66413107d7eccd0
from distutils.core import setup setup( name='dcnn_visualizer', version='', packages=['dcnn_visualizer', 'dcnn_visualizer.backward_functions'], url='', license='', author='Aiga SUZUKI', author_email='tochikuji@gmail.com', description='', requires=['numpy', 'chainer', 'chainercv'] )
7,885
1cdd315eec6792a8588dc2e6a221bc024be47078
import pygame import textwrap import client.Button as Btn from client.ClickableImage import ClickableImage as ClickImg from client.CreateDisplay import CreateDisplay import client.LiverpoolButtons as RuleSetsButtons_LP import client.HandAndFootButtons as RuleSetsButtons_HF import client.HandManagement as HandManagement...
7,886
dc97703d39e7db29e0ba333c2797f4be6d015fd7
# -*- coding: utf-8 -*- """ Created on Mon Apr 16 21:26:03 2018 @author: Brandon """os.getcwd() Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'os' is not definimport os >>> os.getcwd() 'C:\\Users\\Brandon\\AppData\\Local\\Programs\\Python\\Python36-32' >>> os.chdir() Tracebac...
7,887
94ca18088664393fdfdc68bfb8bcad8b78e9e36a
# bot.py import os import shutil import discord import youtube_dl from discord.ext import commands import urllib.parse import urllib.request import re import dotenv from pathlib import Path # Python 3.6+ only from dotenv import load_dotenv env_path = Path('.') / '.env' load_dotenv(dotenv_path=env_path) client = disc...
7,888
4545ce36c4d3df50e263d3323c04c53acb2b50e0
#!/usr/bin/env python3 import csv import math def load_data_from_file(filename): """ Load that data, my dude(tte) :param filename: The file from which you want to load data :return: Time and position data of the file """ time = [] position = [] with open(filename, 'r') a...
7,889
3472dc0c9d00c10ab0690c052e70fbf6a4bdb13d
"""Utilities for AnalysisModules.""" import inspect from mongoengine import QuerySet from numpy import percentile from .modules import AnalysisModule def get_primary_module(package): """Extract AnalysisModule primary module from package.""" def test_submodule(submodule): """Test a submodule to see ...
7,890
19e387cb731dad21e5ee50b0a9812df984c13f3b
import openpyxl as opx import pyperclip from openpyxl import Workbook from openpyxl.styles import PatternFill wb = Workbook(write_only=True) ws = wb.create_sheet() def parseSeq(lines,seqName): '''splits each column''' data = [] for line in lines: data.append(line.split(' ')) '''remov...
7,891
c76fd9b196b50e6fcced7e56517c0cd8ab30e24e
from . import preprocess from . import utils import random import pickle import feather import time import datetime import sys import os import numpy as np import pandas as pd import json from ...main import api from flask import request from flask_restplus import Resource, fields import warnings warnings.simplefilter...
7,892
b3095f181032727544ce3ee6f1ad3a70976c0061
# Copyright (c) 2018-2020, NVIDIA CORPORATION. import os import shutil import subprocess import sys import sysconfig from distutils.spawn import find_executable from distutils.sysconfig import get_python_lib import numpy as np import pyarrow as pa from Cython.Build import cythonize from Cython.Distutils import build_e...
7,893
548c4dbfc1456fead75c22927ae7c6224fafeace
#!/home/porosya/.local/share/virtualenvs/checkio-VEsvC6M1/bin/checkio --domain=py run inside-block # https://py.checkio.org/mission/inside-block/ # When it comes to city planning it's import to understand the borders of various city structures. Parks, lakes or living blocks can be represented as closed polygon and...
7,894
8a4fe88bfa39eeeda42198260a1b22621c33183e
import datetime from threading import Thread import cv2 class WebcamVideoStream: #Constructor def __init__(self, src=0): # initialize the video camera stream and read the first frame # from the stream self.stream = cv2.VideoCapture(src) (self.grabbed, self.frame) = self.stream.read() # initialize the v...
7,895
f82ddc34fde76ddfbbe75116526af45b83c1b102
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # 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 appl...
7,896
9b02ce0b3acb14bdd6463c5bdba865b28253767c
from platypush.message.event import Event class ClipboardEvent(Event): def __init__(self, text: str, *args, **kwargs): super().__init__(*args, text=text, **kwargs) # vim:sw=4:ts=4:et:
7,897
b4f522398cd2658c2db926216e974781e10c44df
import requests #!/usr/bin/env python from confluent_kafka import Producer, KafkaError import json import ccloud_lib delivered_records = 0 url = "https://api.mockaroo.com/api/cbb61270?count=1000&key=5a40bdb0" # Optional per-message on_delivery handler (triggered by poll() or flush()) # when a message has be...
7,898
50ae2b4c6d51451031fc31ebbc43c820da54d827
import math def hipotenusa(a,b): return math.sqrt((a*a)+(b*b)) def main(): cateto1=input('dime un cateto') cateto2=input('dime el otro cateto') print ('la hipotenusa es: '),hipotenusa(cateto1,cateto2) main()
7,899
db920f4aadfb53bb26c5ba1fb182f12b95e14a2f
# Generated by Django 3.1.6 on 2021-02-05 00:27 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main_app', '0001_initial'), ] operations = [ migrations.AlterField( model_name='tea', ...