index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
16,000
81e1d55d476dca19ecbc262bc95398eb0ddacbcf
import os import glob import logging import sys import torch import matplotlib.pyplot as plt from .file_io import * def set_gpu_devices(devices): os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID' os.environ['CUDA_VISIBLE_DEVICES'] = devices print(f'Setting GPU devices is done. ' f'CUDA_VISIBLE_DEV...
16,001
02b9fc8189e61242a35febea03da0a442db59fef
""" Module containing the Blueprint class. This class allows to store an organization of handlers to be used in the construction of a bot """ from .exception.Exceptions import * from .Conversation import Conversation from telegram.ext import Filters class Blueprint(): def __init__(self): self.command_handlers = {} ...
16,002
556ee4b5ee1790b693c0801ef7e985d4f0cec410
#!env/bin/python import time from slackclient import SlackClient from emoji_parser import EmojiParser from command_handler import CommandHandler # starterbot's ID as an environment variable BOT_ID = 'U3YLPLY5C' # constants AT_BOT = "<@" + BOT_ID + ">" EXAMPLE_COMMAND = "do" # read in the authentication token for bot...
16,003
7e71849a1a6d0db36232e4562137ddd76a541205
elemento=[] def separarL(lista): n = int(input("Cuantos valores desea agregar: ")) for i in range(n): no = int(input("Valor: ")) elemento.append(no) i+=1 print(elemento) lista.sort() pares= [] impares=[] for i in lista: if i % 2 ==0: ...
16,004
e219fd5e985f135428a236b5565397a4af403493
# -*- coding: utf-8 -*- import csv from app.cobranza.models import Cobranza from app.investigacion.models import Investigacion init_row = 1 def cobranza_upload(file_path): items = get_items(file_path) save_items(items) def get_items(file_path): index = 0 limit = 1000 items = [] with open(file_path) a...
16,005
f4c120ccffa9fd730c87339c89188138547cb06f
class PStats(): def __init__(self, hp = 0, ep = 0, attack = 0, eattack = 0, defense = 0, edefense = 0, tough = 0, level = 0, XP = 0, AP = 0): self.hp = hp self.ep = ep self.attack = attack self.eattack = eattack self.defense = defense self.edefense = edefense self.tough = tough self.level = level s...
16,006
4a22339d4d84920ed6ef4cfda56c07270e5f5697
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='article', fields=[ ('id', models.AutoField(auto...
16,007
a373f2f883b72e8c9f4061175ba0e8c96a198ea5
import boto3 import json import psycopg2 from django.conf import settings class UploadToPostgres(): def __init__( self, county, rate_energy_peak, rate_energy_partpeak, rate_energy_offpeak, rate_demand_peak, rate_demand_partpeak, rate_demand_overall ...
16,008
36282dcb01840b4e0e1ef803ec7f987e70c7eeaf
import gym import ant_hrl_maze from PIL import Image env = gym.make("AntWaypointHierarchical-v4") env.reset() while True: try: env.render() except KeyboardInterrupt: break while True: inp = input("Action") if inp == "r": env.reset() elif inp == "c": env.render("rgb_...
16,009
668a5fc9e22e71c11b50cc4697c3411cdaca6631
a=int(input()) k=0 while a>0: m=a%10 k=k*10+m a=a//10 print(k)
16,010
f6b1464f09f596f42d5dd94b9dc27ad7d7c92b50
from qt5 import * def main(): app = QApplication(sys.argv) # login = Login() # login.show() # window = MainUI() # window.show() test = Test() test.show() app.exec_() if __name__ == "__main__": main()
16,011
b444203b78a399a4d6fb7bca6b0d816d637d4f9e
#!/usr/bin/python3 # @File:.py # -*- coding:utf-8 -*- # @Author:von_fan # @Time:2020年04月16日23时07分17秒 from rest_framework.views import APIView from .api_response import APIResponse from rest_framework import status class ManyOrOne(APIView,APIResponse): def IsMany(self,request_data): # request_data=request_d...
16,012
0931117495102761435111dcd30fb386e6ecebe3
# map() 함수와 filter() 함수 # map : 리스트의 요소를 함수에 넣고 리턴된 값으로 리스트를 구성해 주는 함수 # filter : 리스트의 요소를 함수에 넣고 리턴된 값이 True인 것으로, 새로운 리스트를 구성해주는 함수 def power(item) : return item * item def under_3(item) : return item < 3 list_input_a = [1,2,3,4,5] # map() 함수를 사용한다. output_a = map(power, list_input_a) print("# map() 함수의 실행...
16,013
db2d630b2825c5d52b8fae389b04f65a830b3120
import argparse import os import json from server import server_start from client import client_start def parse_args(): """ Parses command line arguments Returns: Namespace: Namespace of arguments. """ description = 'Synchronizes files and directories between a client and a server.' p...
16,014
855bfc8dba2e4c13698c599509868b852697be14
#!/usr/bin/python # hashbang, для исполнения скрипта в *nix - системах, указывает интерпретатор # -*- coding: utf-8 -*- # Кодировка файла, необходимо для правильного отображения не англ. строк в интерпретаторе """ Программа реализует примитивный метод шифрования - шифр Цезаря. Сам алгоритм прост - циклициски сдви...
16,015
42674473ebd49442278530e5285b717237f2bb0f
#__author__:"jcm" import os,sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) opts_dir=os.path.join(BASE_DIR,r'data\accounts') def collect_cfg(): cfg_dir_list = [os.path.join(opts_dir,i) for i in [file for a,b,file in os.walk(opts_dir)][0]] return cfg_dir_list
16,016
bac892662b3b4c54f267f17db9254205933d46d6
# -*- coding: utf-8 -*- import numpy import matplotlib.image as mpimg from os import listdir import operator import copy import time def img2vector(filename): img=mpimg.imread(filename) vec=img.copy() return vec def GetTrainData(): filelist=listdir("E:\\深度学习\\训练集数据\\手写字符\\numbers\\train\\") T...
16,017
bac312bfe93abdbec4c061375200c2d60bea8ae5
#!/usr/bin/env python #-*- coding:utf-8 -*- import pandas as pd import tensorflow as tf import random as rn import numpy as np import os from sklearn.metrics import precision_recall_curve, roc_auc_score from keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint, CSVLogger import logging def see...
16,018
f636797571c850ed4eeed7a3372efca90bb450ab
''' Copied from Julian Bautista to be used as a general script to execute eBOSS reconstruction ''' #from ebosscat import Catalog from recon import Recon import argparse from astropy.io import fits import numpy as np from cattools import * dir = '/Users/ashleyross/fitsfiles/' #directory on Ashley's computer where cata...
16,019
670f86bec449206dd9aa1ca65bda6231ae4ee473
# Authored by : gusdn3477 # Co-authored by : - # Link : http://boj.kr/ebf75b738a784d6dad28494e18113b31 import sys def input(): return sys.stdin.readline().rstrip() N = int(input()) X = N for i in range(2, N + 1): if X == 1: break while X % i == 0: X //= i print(i)
16,020
b572fa9f3df07bf5de0644ce8f1f8cc79cc339a0
def backtrack(word,i,j,row,column): if board[i][j]!=word[backtrack.l]: return visited.add((i,j)) #print(visited) backtrack.l = backtrack.l+1 if backtrack.l == len(word): backtrack.found = True return for di,dj in [(1,0),(0,1),(-1,0),(0,-1)]: i1,j1 = i+di,j+dj ...
16,021
f79a8de5d4b5baa4ffffb2523e7bec85495cea3c
import math a=int (input("Enter the number")) print(math.factorial(a))
16,022
3bf85aaf38f6919050d3601608cacab6fcead857
import pickle import torch import torch.nn as nn import numpy as np from bpemb import BPEmb from common.config import PATH VOCAB_PATH = PATH['DATASETS']['COCO']['VOCAB'] EMBEDS_PATH = PATH['MODELS']['WORD_EMBEDS'] def save_vocab(vocab, file_path): with open(file_path, 'wb') as file: pickle.dump(vocab...
16,023
bc5f5b15f68aa2e9d5edb5083b9b5c6e9dce8318
from .base_parser import BaseParser from .const import DIRECTIVE, NUMBER, SYMBOL, NAME, KEYWORD, BOOLEAN, EOF, ANY from .nodes import ( EvalNode, SuiteNode, SkipNode, IfNode, WhileNode, AssignNode, VariableNode, NotNode, ConstantNode, MulNode, SubNode, AddNode, CmpNode, EqNode, AndNode, OrNode, TraceNode, E...
16,024
4cc24de7cba58ab1794c02942198eff84db93f61
#!/usr/bin/env python3 def main(): #"The first line of the input gives the number of test cases, T." t = int(input()) for i in range(t): "Each line describes a test case with a single integer N, the last number counted by Tatiana." ans = solve(int(input())) print("...
16,025
062e61edb7552d6e916034fcbad18b6f740020e1
import numpy as np import cv2 import argparse from features import HoGFeatures, HoGCirclesFeatures from cpp_ottree.tree import Ensemble from normalization import norm_grad, norm_max from utils import DataManager def iou(src, lab): src = (src == 255) lab = (lab == 255) intersection = np.count_nonzero(np....
16,026
88396821e05c0f0d11094d26360e371a4a30f233
# 24. Согласно древней индийской легенде создатель шахмат за своё изобретение попросил у раджи незначительную, # на первый взгляд, награду: столько пшеничных зёрен, сколько окажется на шахматной доске, если на первую клетку # положить одно зерно, на вторую — два зерна, на третью — четыре зерна и т. д. Оказалось, что ...
16,027
56f926c2b9b940a781e7525dda8985d849a17fd8
import numpy as np import pandas as pd # title1 # 背景:数据清洗是数据机器学习中重要的流程之一,数据建模的效果好坏,很大程度上依赖于数据清洗的质量,本案例是银行风控项目中,数据预处理部分的需求,具体要求如下: # 要求: # 1. 读入bank数据表,删除列,列名为每月归还额(10分) # 2. 对指定列做频数统计,列名为贷款期限(10分) # 3. 对指定列做分组统计,列名为还款状态。在此基础上,计算各分组贷款金额列的均值(8分) # 4. 统计贷款金额的均值、最小值、最大值、中位数、方差(6分) # 5. 对数据进行排序,按照发放贷款日期(降序)贷款金额(升序)排序(6分) #...
16,028
6462e116ceeddd1f9a676f40c08663cd92a03708
import os import numpy as N import scipy.ndimage.filters from WEM.utils.exceptions import FormatError class FSS: def __init__(self,data_fcst,data_obs,itime=False,ftime=False, lv=False,thresholds=(0.5,1,2,4,8),ns=None, ns_step=4): """ Fcst and ob data needs to be on the sam...
16,029
1e394957f290ea4b908fede33f3afc72dbb5ce68
from .folks import FolksListener, it_folks, it_attrs, it_changes from kupfer.objects import Source, Action, TextLeaf from kupfer.obj import contacts from kupfer import utils class FolksContact(contacts.ContactLeaf): def __init__(self, obj): self.folk = obj slots = {contacts.LABEL_KEY: obj.get_d...
16,030
9440453f4de955bee68c4d08b367a8befcfc81c3
#!/usr/bin/env python # encoding: utf-8 import sys reload(sys) sys.setdefaultencoding('utf8') from bs4 import BeautifulSoup import re import urllib2 import xlwt #得到页面全部内容 def askURL(url): #发送请求 request = urllib2.Request(url) try: #取得响应 response = urllib2.urlopen(request) #获取网页内容 html= resp...
16,031
2e07f784a9a9430f51359bf380aaeed3cf8fb3a1
import argparse import math import subprocess def read_pred_file(file_name, args): fin = open(file_name) result_list = [] qid_list = [] docid_list = [] pair_list = [] for line in fin: items = line.strip().split() qid = int(items[0]) docid = int(items[2]) score = ...
16,032
68ec55811486be28d037b4cf4e69b792be745973
# -*- coding: utf-8 -*- """ Created on Wed Aug 18 20:23:42 2021 @author: chanchanchan """ import streamlit as st import pandas as pd import plotly.graph_objects as go def app(): st.header('Summary of Shear Wave Velocity') st.write('The data used in this bender element anaylsis were ...
16,033
484ccf8dac1bc814cbf6d9cab62d4f0ada0094f8
""" Capstone Team Project. Code to run on a ROBOT (NOT a laptop). This module intentionally has NO main function. Instead, the one and only main function for ROBOT code is in module m0_run_this_on_ROBOT When m0_run_this_on_ROBOT runs, it calls its main to construct a robot (with associated objects) a...
16,034
c9e8a25d61502618eee6ad656e1c2ce892264093
from igf_data.igfdb.platformadaptor import PlatformAdaptor from igf_data.utils.dbutils import read_dbconf_json, read_json_data def load_new_platform_data(data_file, dbconfig): ''' A method for loading new data for platform table ''' try: formatted_data=read_json_data(data_file) dbparam=read_dbconf_json...
16,035
9150e8f24842ffe38e4f663352c8694c1beff9a7
import numpy as np import math all_crd = [] center_crd = [] rotated_crd = [] prefix = [] appendix = [] matrixA = np.array([[],[],[]]) matrixB = np.array([[],[],[]]) def vector_gen(atomX,atomY): vector = [0]*3 vector[0] = float(all_crd[atomY*3-3]) - float(all_crd[atomX*3-3]) vector[1] = float(all_crd[atom...
16,036
4c8572da10545466ca3b1b3157cc41a6810b8706
from unittest.mock import Mock import pytest from shopping.repeatingitems.shopping_repeating_items_worksheet import RepeatingItemsWorksheet, \ RepeatingItemsAlreadyPresent ALL_VALUES = ["item-1", "item-2", "item-3"] @pytest.fixture def generate_repeating_items_worksheet(): worksheet_mock = Mock() works...
16,037
0bf8ecc1859e4fb02594fa6267770a2cc266a3ef
# http://codecombat.com/play/level/serpent-savings # todo this logic need to be improved # You cannot collect coins. # Summon peasants to collect coins for you. # Collecting coins spawns a growing 'tail' behind the peasants. # When a peasant touches a tail, they die. # Collect 500 coins to pass the level. # The followi...
16,038
10098591081162b8083fda0f96632512ba91ff22
# dependencies from config import database, connect_string # relational database class with our data retrieval functions from BellyButtonData import BellyButtonData # mongodb database class with the same function signitures ( same functions) from BellyButtonMongo import BellyButtonMongo from flask import Flask, jsoni...
16,039
4192269b478dafff0c986ea7ebbc504327c0e42f
import requests import csv import getpass # Set the request parameters # Change the URL according to what information is desired. subdomain = input("Enter your Zendesk Subdomain (not full URL, but something such as your company name): ") url = 'https://' + subdomain +'.zendesk.com/api/v2/help_center/en-us/articles.jso...
16,040
d9cf562a37c2c5f12cf2f85f29e67df8a212e6e1
import unittest from chenyao.CLASS.members import MemberHelper class TestMemberHelperLast(unittest.TestCase): @classmethod def setUpClass(cls): print('1.setup test class') @classmethod def tearDownClass(cls): print('2.teardown test class') def setUp(self): print('3.set up ...
16,041
efa21870f583e66115ceb635a48bc13efc727b5b
#!/usr/bin/python3 """ module containts unittests for class Review """ import unittest import json from models.base_model import BaseModel from models.review import Review class testReview(unittest.TestCase): """ unittests for Review """ def setUp(self): """ Sets up the class """ self.revie...
16,042
f5def2c87945663fa80b2f5f29795f2be8fb46de
# aList=[1,2,3,4,5,6,3,8,9] # sign=False #初始值为没找到 # x=int(input("请输入要查找的整数:")) # for i in range(len(aList)): # if aList[i]==x: # print("整数%d在列表中,在第%d个数"%(x,i+1)) # sign=True # if sign==False: # print("整数%d不在列表中"%x) # # # # # def binary_chop2(alist, data): # """ # 递归解决二分查找 # ""...
16,043
9499ec765a7b24681b102f860cd83ddb1cabad78
import asyncio from moex.models import Price from scripts.main import get_history_price def pull_price(security, start, end): data = asyncio.run(get_history_price(security.code, start, end)) batch = [Price(date=price['TRADEDATE'], price=price['CLOSE'], security=security) for price in data] Price.objects.b...
16,044
69e398c891b5ceacbc31b2cbe3d880032428acc9
class SomeClass(object): @property def x(self): return 5 def y(self): return 6 var = SomeClass() print(var.x) print(var.y)
16,045
1137435538552accb0053f02bf3c141489561e58
import pandas if __name__ == '__main__': df=pandas.read_excel("you_chongfu_data.xlsx") print("去重之前总数:",df.count()) df=df.drop_duplicates() print("去重之后的总数",df.count())
16,046
53d3d83d892e8330ecd5edbdca384fb0edb8b25e
from upthor.views import FileUploadView from django.conf.urls import url urlpatterns = [ # for Testing url('^thor-upload/', FileUploadView.as_view(), name='thor-file-upload'), ]
16,047
962419ab6b62b0ba358aaff100d8e6cf36fc17c5
ls = [10,20,20,40] for element in ls: #print(element) pass for char in "techcamp": #print(char) pass student = { "name": "Emma", "class": 9, "marks": 75 } for each in student: #print(each,student[each]) #print("Key : {} , Value : {}".format(each,student[each])) pass for k,v in ...
16,048
eaf15eafcd58d3b458ca1d3c402b421ff1e69085
from .basefuncs import * try: from functional import compose except ImportError: raiseErrN("You need functional!\nInstall it from http://pypi.python.org/pypi/functional\nor run pip install functional.") def ParserError(message, token): # print(token) raiseErr("ParserError: %s '%s'" % (message...
16,049
858192871464e7a3d8750427088dcbd0f72959db
from __future__ import division, print_function, unicode_literals # This code is so you can run the samples without installing the package import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) # testinfo = "t 0.1, s, t 1.1, s, t 2.1, s, t 3.1, s, t 4.1, s, t 5.1, s, t 6.1, s, q" tags ...
16,050
67951f9e69587eb49ed4ce2e047f21185474c821
# permitted by applicable law. You may use it, redistribute it and/or modify # it, in whole or in part, provided that you do so at your own risk and do not # hold the developers or copyright holders liable for any claim, damages, or # other liabilities arising in connection with the software. # # Developed by Mario Va...
16,051
6be7979ac5ff37416b819085091b09e17418aa76
###Marie Hemmen, 05.09.16### import sys from shmooclass import shmoo from spline_interpolation import Spline_Interpolation import numpy as np from PIL import Image from matplotlib import pyplot as plt import scipy from scipy import misc from scipy import ndimage import math import pdb import Image from random import r...
16,052
ca2aab6bdb63625b96096dc17bee9659e15360d7
from data_structures_and_algorithms.challenges.array_binary_search.array_binary_search import binary_search """ test empty array test the odd number in sotred array test the even number in sotred array """ def test_works_if_empty_arr(): actual = binary_search([], 2) expected = -1 assert expected =...
16,053
74d5fafee5b48119f0d767d1be2ac2240030bcdd
N=int(input()) print(N*(N-1)//2 if N>2 else 1 if N==2 else 0)
16,054
f55fa7dfd5d75769fbdd1f12b48dc202f59db548
# Generated by Django 3.1.7 on 2021-04-05 19:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('limbo', '0003_auto_20210329_2015'), ] operations = [ migrations.CreateModel( name='DefaultList', field...
16,055
e64fe5f94d5159b21f0bb4d846a0f28ff75dc9c4
''' RULES: 1. All tetrominoes spawn horizontall and wholly above the playfield 2. I, O tetrominoes spawn centrally, while 3-cell wide tetrominoes spawn rounded to the left 3. J, L, T spawn flat-side first ''' import pygame import time from time import sleep import random import math from block_sh impo...
16,056
09c9e4aea40a3da12ca16385faa8dedd23e45098
import numpy as np import matplotlib.pyplot as plt import pandas as pd from pylab import * from matplotlib.colors import ListedColormap from perceptron import Perceptron def decision_region(X, y, classifier, resolution = 0.02): df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris...
16,057
915960b82cfea6ed7247cc36fdd8671610a9d9f5
from api import main_api base_url = "https://api.reliefweb.int/v1/reports?appname=apidoc" def get_reports_for_country(iso_code): reports = [] for ocha_product in 20471, 12347, 12348, 12354: # https://api.reliefweb.int/v1/references/ocha-products report = main_api.call_get( url=base_url ...
16,058
a67b67e949ee14978148bab03d81f0b2ca1efaa9
from django.shortcuts import render,redirect from apps.Tienda.models import Categoria from apps.Tienda.models import Producto from apps.Tienda.models import Ventas from django.views.generic import ListView from apps.Tienda.forms import ProductoForm from apps.Tienda.forms import CategoriaForm from apps.Tienda.for...
16,059
30c48ffc95e10d5b50d667f185fff349c80de32d
/home/runner/.cache/pip/pool/0b/cd/ab/c0557d6742d41ea7191fdf6322937500d409fcabfe599c041b56d75c26
16,060
cf5dcb4cbcdb7962f510ce4af9c459b761b4ef33
import logging import os from google.appengine.ext import db from google.appengine.ext.webapp import template from google.appengine.api import users import jinja2 import webapp2 jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) ROOT_PATH = os.path.dirname(__fi...
16,061
26ddbe6177d35aac60169168ca81b1cc13ead72d
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-16 19:15 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('movies', '0008_movie_title_sort'), ] operations = [ migrations.RenameField( ...
16,062
06e79743bff04ec5bf180bcfa8e77c063a62db71
from itertools import combinations N = input() nth = len(N)-1 N = int(N) for val in combinations()
16,063
1ac038fdc3d48d498331cde0c840e88a70bf1860
# -*- coding: utf-8 -*- import telebot import json from os.path import exists triggers = {} tfile = "chatter_data.json" separator = '||' if(exists(tfile)): with open(tfile) as f: f = open(tfile) triggers = json.load(f) print("[Chatter] Loaded data.json file.") else: print("[Chatter] C...
16,064
1ba0703aa45f7c58ec4831579fcf3ee4d11b3f8b
# This script copies over the native protein structure for each pdb id and # randomly samples decoys for each native structure. These pdb files are saved # in another folder called 3DRobot_subset. # 0. Loading the relevant packages-------------------------------------------- import os import numpy as np import pandas...
16,065
f7648ce474bfaeb15b0825681721c9ab06d7c138
# -*- coding: utf-8 -*- from vablut.modules.ashton import * from vablut.modules.tables import _indices from random import randint import pytest def test_colrow(): #ashton rules required 9x9 board assert col == 9,"Ashton rules: col must be 9 not %s"%col assert row == 9,"Ashton rules: row must be 9 not %s"%...
16,066
1d949db0e3a278385661000273714abf339798bd
from .wordnet_mapper import WordNetMapper from . import attribute_mapper from . import relationship_mapper
16,067
2b1d9d040d0cd1ef5478ad23fdd5804a87b78007
import numpy as np import pandas as pd def datapoints_f(path): ''' This function takes the raw data and changes it into a numpy array and a result_vector, with the array's columns being each datapoint. Assumes path is a string ''' df=pd.read_csv(path,delim_whitespace=True,names=['x','y','result']) ...
16,068
29e67fdc269c8c58f19021e4f429c549e473cf11
# _*_ encoding: utf-8 _*_ ''' Created on 2016年3月16日 @author: carm ''' from pylab import plot, show, figure, subplot, hist, xlim class DataDrawing(object): def draw_two_dimension_spot(self,data,target): """ 使用第一和第三维度(花萼的长和宽) 在上图中有150个点,不同的颜色代表不同的类型; 蓝色点代表山鸢尾(setosa),...
16,069
6ad0d15444d9a7ac297b059598da33e8aada3cc0
## Abstract superclass for all formatters. Each formatter defines a list of # relevant file extensions and a run() method for doing the actual work. class Formatter: def __init__(self): self.file_extensions = [] self._config_file_name = None ## Adds any arguments to the given argparse.ArgumentP...
16,070
01d59de2b3b90eac0eabe882c4ffc8b63e2e7521
def remove_smallest(numbers): return [v for i, v in enumerate(numbers) if i != numbers.index(min(numbers))]
16,071
b0536f628c48254d64e428401bd5a13ca1b07c30
class KeyValueStorage: def __init__(self, path): with open(path, "r") as file: data = file.read().splitlines() for line in data: key, value = line.split("=") if not key.isidentifier(): raise ValueError("Wrong key!") ...
16,072
7469061842a49c2b06a0567a9de0c11c02e8b456
#!/usr/bin/env python3 from sys import argv a, b, c, = int(argv[1]), int(argv[2]), int(argv[3]) if (a >= b + c) or (b >= a + c) or (c >= b + a): print("False") else: print("True")
16,073
63662220c3ac36cde6ddab964391e327a5be3ec8
import json from bson import json_util from bson.json_util import dumps from pymongo import MongoClient connection = MongoClient('localhost', 27017) database = connection['market'] collection = database['stocks'] def findDocument(query): try: line = "--" * 45 result=collection.find(query).count() print...
16,074
4ca26eaf039f808879dc44ea500ca94051d4449e
import serial import time ser = serial.Serial('/dev/ttyACM0', 9600) time.sleep(2) if ser.isOpen(): print "Port Open" print ser.write('s'.encode()) ser.open() ser.close()
16,075
8b415429538cbcf3d4dba60ed4d03cdd29ba44bc
import math #The following function converts a decimal number into a 'bit'long binary number def bin(num, bit): i = 1 s1 = [] a = "" while(i<=bit): s1.append("0") i = i + 1 k = num rem = 0 if k==0: return "".join(s1) i = 0 while(num>0): rem = num%2 num = num/2 s1[i] = str(rem) i = i + 1 return ...
16,076
7fb9f3b635ca4ba187ae55be9447b3c129c448c0
from urllib.parse import urlparse from twisted.internet import reactor from twisted.names.client import createResolver from scrapy import Spider, Request from scrapy.crawler import CrawlerRunner from scrapy.utils.log import configure_logging from tests.mockserver import MockServer, MockDNSServer class LocalhostSpi...
16,077
c207416c5b0708b1198faa1934baa29c2ea82a17
import random computer_wins = 0 player_wins = 0 while True: print("") user_choice = input("Choose Rock, Paper or Scissors : ") user_choice = user_choice.lower() moves = ["rock","paper","scissors"] comp_choice = random.choice(moves) print("") if user_choice == "rock": if co...
16,078
2148b883a656e280e7842465ee4df90fb0b7ef26
from django.conf.urls import url, include from django.urls import path from rest_framework.routers import SimpleRouter from chat import views from chat.views import ChatRoomViewSet from chat.views import ChatMessageViewSet router = SimpleRouter() router.register('chatroom', ChatRoomViewSet) router.register('chat', Ch...
16,079
1f7d678a3b1003cb19ddf1b95fd159364fb847d4
''' 字符串 ''' s="hello" # print(len(s)) # print(s[1]) # for i in range(0,len(s)): # print(s[i]); # print(s[7]) # print(s[4]) # print(s[-1]) #字符串切片 # line="zhangsan,20" # name=line[0:8] # print(name) # # age=line[9:] # age=line[9:11] # print(age) s="abcde" print(s[0::2])
16,080
58135123b7f23c946749e6c7369f5ca4d0c39dfa
# if conditon for boolean check = True if check: print("true block") # if else check = False if check: print("True block") else: print("False block") # if condition number = 5 if number == 5: print("number is 5") ''' When we need to check if its a number/string , no need to be check if its exactly e...
16,081
c6a47dc23e94afe8b8a7156d41018b786c75fbc8
import os import luigi import pptx from typing import List from luigi.contrib.external_program import ExternalProgramTask from datetime import datetime from dateutil import tz class PrintDate(luigi.Task): pptx_filename: str = luigi.Parameter() workdir: str = luigi.Parameter() def requires(self): r...
16,082
48e52fd64bf177d4431d12c26ba357047d918887
import sys, random, os class Monster(object): exp = 0 level = 1 decay = 0 def __init__(self, name, atk, arm, hp, spec, nextLevel, regen): self.name = name self.HP = hp self.atk = atk self.armor = armor self.spec = spec self.maxHP = hp self.nextLe...
16,083
579bc998ad5c8725d13c09f6bc240aea057d8788
import sys, os import shutil from castepy import castepy from castepy import constraint from castepy import cell from castepy import calc from castepy.util import calc_from_path, path relax_path = path("templates/spectral") merge_cell = cell.Cell(open(os.path.join(relax_path, "spectral.cell")).read()) def make(sourc...
16,084
936eff3263b72709bc11f873707b1711f2549e37
''' Design an algorithm that computes the successor of a node in a binary tree. Assume that each node stores its parent. Hint: Study the node's right subtree. What if the node does not have a right subtree? ''' import unittest from binary_tree import BinaryTree def get_node_successor(n): if n['right']: n ...
16,085
6c1cc62baaf73268bd6688b967a6f2b51224991c
import numpy as np import pandas as pd # import seaborn as sb import matplotlib.pyplot as plt # from sklearn.decomposition import PCA from sklearn.naive_bayes import GaussianNB from sklearn import linear_model from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import PolynomialFeatures def anal...
16,086
cf60eb9a0f33939d01cded5df52bf20815bb5fc3
import numpy as np np.random.seed(5) b0 = 2 b1 = 1 N = 100 step = 0.2 mu = 0 # pas de biais sigma = 10 x = np.random.randn(int(N/step))*5 # x = np.arange(0, N, step) e = np.random.normal(mu, sigma, int(N/step)) y = b0 + b1*x + e import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(8, 4)) ax.scatter(x, y,...
16,087
9fe40a62e818cc8eb1890f5fe505014dfa81173e
class MemberStore: members = [] def get_all(self): return(MemberStore.members) def add(self, member): self.members.append(member) class PostStore: posts=[] def get_all(self): return (PostStore.posts) def add(self,post): self.posts.append(post)
16,088
b7fa0c4f24acdd4140bfff8f4b2afe2c4e09fcf2
from django.http import HttpResponse import json class JSONResponseMixin(object): def render_to_response(self, context): """Returns a JSON response containing 'context' as payload""" return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs):...
16,089
a378350a741aeae0928b39285306374a19fc8d44
from selenium import webdriver from utils import * PATH = 'C:\Program Files (x86)\chromedriver.exe' # Path to chrome driver USERNAME = 'adming' # wordpress username PASSWORD = 'admin' # wordpress password driver = webdriver.Chrome(PATH) if __name__ == '__main__': # Loading my localhost server that contai...
16,090
c33df9d1befde8dae72385d43ce5b185a187da6d
def solution(answers): tmp = [] cnt = 0 cnt_lst = [0,0,0] p1 = [1,2,3,4,5] * ((len(answers) // 5)+1) # enumerate 써서 idx%len(p1) 하면 초기화 늘려줄 필요 없음. p2 = [2,1,2,3,2,4,2,5] * ((len(answers) // 8)+1) p3 = [3,3,1,1,2,2,4,4,5,5] * ((len(answers) // 10)+1) for i in answers: if p1[cnt] == i:...
16,091
ac3abe2518f838e05c02ddca7fe38794db66ba0f
lst = [1,2,4,3,5] for x in lst: if x % 2 == 0: lst.remove(x) print(lst) # create a shallow copy of the list for x in lst[:]: if x % 2 == 0: lst.remove(x) print(lst) s = 'beautiful' for ch in s: if ch in "aeiou": s = s.replace(ch, '') print(s)
16,092
26759fbe839a9c0d5a7436576820f261f8267d5d
from django.urls import path from . import views urlpatterns = [ path('get_profile/', views.get_profile, name="get_profile"), path('logout_profile/', views.logout_profile, name="logout_profile"), path('show_my_profile/', views.show_my_profile, name="show_my_profile"), path('update_my_profile/', views.update_my_pro...
16,093
e29e3225baf54051c387c22fbcf059708ac116c9
import os __author__ = 'huanpc' from influxdb import InfluxDBClient import xml.etree.ElementTree as ET def store_data(xml_data=None): root = ET.fromstring(xml_data) ipe_id = root.find('./*[@name="ipeId"]').attrib['val'] app_id = root.find('./*[@name="appId"]').attrib['val'] category = root.find('./*...
16,094
187413036295bf7a131bfe9d1c159c5cb9b8e070
import unittest import ControllerElenco class TestElenco(unittest.TestCase): def setUp(self): ControllerElenco.RemoverTodosElenco() def test_sem_ator(self): elencos = ControllerElenco.BuscarTodosElenco() print (elencos) self.assertEqual(0,len(elencos)) ...
16,095
24498da6c33aa995c22b22debc289136866b0939
# Ref: https://leetcode.com/problems/stickers-to-spell-word/discuss/108318/C%2B%2BJavaPython-DP-%2B-Memoization-with-optimization-29-ms-(C%2B%2B) class Solution(object): def minStickers(self, stickers, target): num_sticker = len(stickers) s_cnt = [collections.Counter(s) for s in stickers] ...
16,096
841b1962acc5208728c6d61e272b646adc1fbe17
import tkinter as tk app_state = {"counter": 0} window = tk.Tk() hello_label = tk.Label(master=window, text="Hello!") hello_label.config(text="Hi!") hello_label.pack() message_label = tk.Label(master=window, text="") message_label.pack() def display_message(): message_label.config(text="Hello!") hello_butto...
16,097
43d0538b3b53bd4c9c86134b7d7d392684c8aff8
# セミコロンは要らない x = 1 y = 2 # 1行は80文字以内 x = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' # 変数が長くなりそうなときは2行にする def test_func(x, y, z, foperfjesoigntdrhoydjthktypgaejrpesotgmprsdmponbkf='test'): """ :param x: :param y: :param z: :param foperfjesoigntdrhoyd...
16,098
a7a5553f5fa371a0a30635d5a53dc4f8ba1aa4f8
#Equal dict or not d={1:'abc',2:'def'} d1={1:'abc',2:'def'} print(d==d1)
16,099
3ffc9bab51adf22e9582b310da7384f501cd7f69
#Solution Code to CS50 Ai course Tic tac toe's problem by Alberto Pascal Garza #albertopascalgarza@gmail.com """ Tic Tac Toe Player """ import math import copy from random import randint X = "X" O = "O" EMPTY = None def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EM...