index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
989,900
09c9bb2d3f9f6ca33e240337992f37fe3d9ee088
import sys filepath = sys.argv[1] filepath_out = sys.argv[2] preranked_file = sys.argv[3] preranked = [] # (topic, doc id, score) score is 0,1 if qrel with open(preranked_file, 'r') as inputFile: for line in inputFile: parts = line.split() preranked.append((int(parts[0]), parts[2].strip(), parts[...
989,901
73f10ac155c1717dfdf19e8e10c3ef14b00e3ccb
def bubble_sort(array): n = len(array) for i in range(n - 1): for j in range(n - 1 - i): if array[j + 1] < array[j]: array[j + 1], array[j] = array[j], array[j + 1] return array a = [1, 2, 1, 3] print(bubble_sort(a)) def quicksort(array): n = len(array) if n <= ...
989,902
abaad1060835d3edbf82ae8aeeefa94fd4541efe
import os.path from pathlib import Path import googlephotos_helper import settings def upload_to_google_photos(pics): print(f'Uploading to google photos...') if len(pics) > 0: session = googlephotos_helper.get_session() # 古い画像からアップロードしたほうが並び順的にいい感じだと思うのでreversedにしておく googlephotos_help...
989,903
dab0a91a19e2a4b42deea6b066724286f6112c4a
#선택정렬 from random import randint array =[] for j in range(0, 100): array_num = randint(1, 100) array.append(array_num) for i in range(len(array)): min_index = i for j in range(i+1, len(array)): if array[min_index] > array[j]: min_index = j array[min_index], array[i] = array[i], array[min_index] #스와...
989,904
9d60c2ae1c08f144030d959d354735ef285fd61f
name = 'Da Woon CHAE' age = 23 # not a lie height_cm = 176 # centimeter cm_to_inch = 1.0 / 2.54 height_inch = height_cm * cm_to_inch weight_kg = 72 # kilogram eyes = 'Black' teeth = 'White' hair = 'Black' print "Let's talk about %s." % name print "He's %g inches tall." % height_cm print "He's %g inches tall." % height...
989,905
c15c30a4fca05a2887beba2a4efa325bfce4d151
# -*- coding: utf-8 -*- """ This is a skeleton file that can serve as a starting point for a Python console script. To run this script uncomment the following lines in the [options.entry_points] section in setup.cfg: console_scripts = fibonacci = ideuy.skeleton:run Then run `python setup.py install` whic...
989,906
598badfa716e489f2a6877b4c1450f7ca6b0a335
with open("day-08.txt") as f: notes = [line.split(" | ") for line in f.read().rstrip().splitlines()] patterns = [] outputs = [] for p, o in notes: patterns.append([tuple(sorted(s)) for s in p.split(maxsplit=9)]) outputs.append([tuple(sorted(s)) for s in o.split(maxsplit=3)]) def make_mask(digit): mas...
989,907
c0d8fa17087bd12ee9bd1fb9cf58dd0cc3d5bf6c
from scipy.io.wavfile import read import matplotlib.pyplot as plt # read audio samples print("Enter the digit for the different Sound wave") i=input('Enter your choice') input_data = read("Sound/leftByAnkur1.wav") if i== '1': input_data = read("Sound/leftByAnkur1.wav") elif i== '2': input_data = read("Sound/le...
989,908
20eae8ab1bc6a1242d548efb8a9ed509ea8398ef
from math import pi from math import sqrt import sys r = float(sys.argv[1]) d = 2 * r p = 2 * pi * r a = pi * r **2 soluciones = input ("Elige una de las siguientes soluciones (diámetro(d), perímetro(p), área(a) o salir(s): ") if soluciones == "diámetro" or soluciones == "diametro" or soluciones == "d": print(d)...
989,909
fc110134e48dcaa8bbc5d8284108f8d3e397c762
import time import beeper seconds = input("how many seconds? [q for quit] ") while seconds != "q": seconds = int(seconds) while seconds > 0: print(seconds, "remaining") time.sleep(1) seconds -= 1 print("beep beep beep") beeper.beep(3) seconds = input("how man...
989,910
b79d749f3dcb893303f9148c6cec8540b49c0ce2
from typing import Callable, List, Union import random import cv2 import numpy as np from vcap.caching import cache class DetectionPrediction: def __init__(self, class_name: str, class_id: int, rect: List[Union[int, float]], confidence: float): """An ob...
989,911
f813a1f39db7fc32ad0b33967f6bbaad5c163877
#!/usr/bin/env python # coding: utf-8 # In[1]: from __future__ import print_function import os import numpy as np import cv2 import os import sys stderr = sys.stderr sys.stderr = open(os.devnull, 'w') import keras sys.stderr = stderr import tensorflow as tf os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' from keras.models...
989,912
b9e3d8d0e066b309d91acfcb997ec093c8b6ed32
dicci={"Alemania":"Berlín", "Francia":"París", "Colombia":"Bogotá", "España":"Madrid"} print(dicci["Francia"]) #Agregar mas elemnetos dicci["Italia"]="Lisboa" print(dicci) #MOdificar dicci["Italia"]="Roma" print(dicci) #Eliminar del dicci["Italia"] print(dicci) #Diccionario con distintos tipos de datos dicci2={"Nombre"...
989,913
82a820be663fa7fc7726b6f259aee4db2e7c727f
#!/usr/bin/env python3 # -*- encoding: utf-8; py-indent-offset: 4 -*- # (c) Andreas Doehler <andreas.doehler@bechtle.com/andreas.doehler@gmail.com> # This is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation i...
989,914
08d4ac34068d405f1edc0c39216cfb3db7e06cf7
# -*- coding: utf-8 -*- #PYTHON SCRIPT #X X SCRIPT NEEDED FOR VOLTAGE TEMPERATURE CALCULATION OF THE IPG LEAD #THE MODEL SHOULD BE ACTIVE AND SIMULATION RESULTS OF THE MODEL SHOULD HAVE BEEN COMPLETED BEFORE THE SCRIPT IS RUN # original code modified by cfawole #owning U of H code #extract human body electric fields...
989,915
b7acda9f0bf4d912e1e62f7f08a734d2320df779
# -*- coding: utf-8 -*- from formencode import validators from tw2.forms import ( TableForm, TextField, TextArea, LabelField, ) from tw2.tinymce import TinyMCEWidget from pylonsprojectjp.apps.admin import ( admin_config, ListColumn, ) from .models import BlogEntryModel class BlogEnt...
989,916
ecc8050a55cc3113e34809d0d49e27a701c91c73
import random def random_move(): direct = ("up", "down", "left", "right") if random.randint(0, 1): return random.choice(direct) else: None
989,917
1decbe4ef0566adaba5bd736f2c16c0a84a83ef0
import datetime import glob import os import time from django.conf import settings from django.template.loader import render_to_string from ietf.message.models import Message, SendQueue from ietf.message.utils import send_scheduled_message_from_send_queue from ietf.doc.models import DocumentAuthor from ietf.person.mo...
989,918
823122629e28be046da527979da2b30fab51a378
from .__core import * __all__ = ["routine"]
989,919
069933f4e265a70a118a9584e9b1daa79922d925
from config import Config from subprocess import Popen, PIPE class Set(): def __init__(self) -> None: config = Config() self.config = config.read() def command(self, label: str) -> None: monitors = self.config[label] command = ['xrandr'] for monitor in monitors: ...
989,920
9246472296156ed6e754fc6d5ca540a47c30f439
import random # stolen from https://github.com/arizonatribe/word-generator class Words: words = { "nouns": [ "aardvark", "aardwolf", "ability", "abroad", "abuse", "accentor", "access", "accident", "account", ...
989,921
4aab0f7ea5f48d28b25a456fb24a9830fa9a434f
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2018-03-27 09:01 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('project', '0019_auto_20180327_1614'), ] operations = [ migrations.AlterFiel...
989,922
7a940f3b1404b976dae70ab9c3bfb0ac4ab1147e
import numpy as np import torch from tqdm.auto import tqdm import torch.optim as optim from pathlib import Path import utils import os from dataloader_cache_allitem import DataLoaderTrain, DataLoaderTest from infer_embedding import news_feature, infer_news_embedding from preprocess import read_news_bert, get_doc_input...
989,923
2fff0ca5417b2c52037dac5abee7849a65d9469c
import turtle as t import random tort = t.Turtle() t.colormode(255) tort.shape("turtle") def random_color(): red = random.randint(0, 255) green = random.randint(0, 255) blue = random.randint(0, 255) random_colour = (red, green, blue) return random_colour tort.speed('fastest') def draw_spirog...
989,924
7d81651e37330abf932263d3ba4f5f4544d3f355
import random, time, sys #import numpy as np #from pygame.locals import * import pyjsdl as pygame #import pygame from textdata import txtFile #pyjsdl.display.setup(runGame) WINDOWWIDTH = 500 WINDOWHEIGHT = 700 boardArrHeight = 200 boardArr = [] posX = 5 #chracter position posY = 0 direction = "down" score = 0 stomach...
989,925
28bdbc25d691bed614bf2d9e8256dd342de60c9e
from django import forms from django.conf import settings from django.core.mail import send_mail from django.template import loader from django.template import RequestContext from django.contrib.sites.models import Site from apps.captcha.fields import CaptchaField from django.utils.translation import ugettext_lazy as _...
989,926
5cd3d855f4b90bda54964365387e39186c00844a
""" Taken from and somewhat expanded upon: https://towardsdatascience.com/streamlit-101-an-in-depth-introduction-fc8aad9492f2 The examples in the article don't jibe with the actual output in a number of cases. I've added some of my own workarounds, but the original code is here https://github.com/shaildeliwala/experim...
989,927
374de701f733b4b76fe5df5b5e0aa090b93650bd
"""Helper module to compute for the Shapley values of each feature Authors: Leodegario Lorenzo II, Alva Presbitero Date: 13 October 2021 """ from math import factorial def compute_shapley_value(model_outcomes, feature_name): """Return the Shapley value of the feature given model outcomes dictionary Par...
989,928
d55347bf34909f2329b599c6795d15ce90c2ecfb
""" Author : Kusmakhar Pathak Created: 30 July 2020 (c) Copyright by Kusmakhar Pathak. """ # Programme to get hostname and host IP address import socket # function to access host computer IP address def get_ipAddress(): host_pc = socket.gethostname() IPAddress = socket.gethostbyname(host_pc) return ho...
989,929
37e741f68de5ce3e13e591d8439263ae063a7026
def webapp_add_wsgi_middleware(app): #from google.appengine.ext.appstats import recording #app = recording.appstats_wsgi_middleware(app) return app remoteapi_CUSTOM_ENVIRONMENT_AUTHENTICATION = ( 'HTTP_X_APPENGINE_INBOUND_APPID', ['literumble'])
989,930
138edf31e63fa233586a6395fd733e0b415c2554
##A palindromic number or numeral ##palindrome is a number that remains the same when its digits are reversed. x = int(input("enter the first number. ")) y = x sum = 0 while y > 0: i = y % 10 sum = sum * 10 + i y = y // 10 if x == sum: print (x, "is an palindrome number") el...
989,931
e221114c95418f03dd2f426c3ec6746ecc763f0b
# Julita Osman 314323 # http://pep8online.com/ def is_palindrom(text): text = text.lower() length = len(text) lista = [' ', '.', ',', ':', ';', '-', '\"', '?', '!', '\''] for i in range(length): k = length - i - 1 if text[k] in lista and length-1 != k: text = text[0:k:]+tex...
989,932
5615a7f29fb34b8bf40dc9c2f5afabe914313089
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-19 14:26 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wf', '0002_auto_20170919_1343'), ] operations = [ migrations.RenameField( ...
989,933
33b24f5a26b1493385f91feaa29c59653bd00a96
f = open("C:/Users/escroc/Documents/projectBioInformatique/Supp-B.txt", 'r') # # while(f.read()): # print(text) data ="" for line in f: if not line[0].isdigit(): data+=line print(data) save = f = open("C:/Users/escroc/Documents/projectBioInformatique/Supp-B-prunned.txt", 'w') save.write(data)
989,934
1988c4a636e7ce828cb28320f569025f8270b98c
''' Take in the following three values from the user: - investment amount - interest rate in percentage - number of years to invest Print the future values to the console. ''' investment_amount = int(input("Amount of investment: ")) interest_rate_in_percentage = int(input("interest rate (%): ")) number_o...
989,935
beb1be5397da229a4e90f891efa3c8dfefa53153
from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import classification_report, confusion_matrix from sklearn.ensemble import GradientBoostingClassifier from xgboost import XGBClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score import pandas as pd...
989,936
d14c054329c2ce1b80d367af715e98b61604c65e
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'D:\Codes\PyQt5Projects\blogui\RightSearchWidget.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_RightSearchWidget(object): ...
989,937
38b0dd6836f1e97476f1e8cb2950165cc39e4924
# Generated by Django 4.1.7 on 2023-02-21 09:05 import ckeditor.fields from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Player', fields=[ ('...
989,938
50d8db2038a018a20fb3a5c535d2cd303816d31d
def gallery_creator(img_list): for image in img_list: print('\'<a href="http://plonsker.github.io/imgs/' + image + '" target="_blank"><img src="imgs/' + image + '"/></a>\',') img_list = ['00(1).tiff','000008190022.jpg','000012590002.jpg','000012590035.jpg','000012700008.jpg','000012700019.jpg','000012700021.jpg'...
989,939
e26e8276882ddb37695bdc81c7968fdb5346b7cb
import numpy as np import pyautogui import imutils import cv2 template = cv2.imread('Alive.png') img_original = pyautogui.screenshot(region=(18,400, 772, 194)) img_original = cv2.cvtColor(np.array(img_original), cv2.COLOR_RGB2BGR) img_rgb = cv2.cvtColor(np.array(img_original), cv2.COLOR_RGB2BGR) w, h = temp...
989,940
134cfaa5150df3331864c5c8dc9ce7f0d9a6d13e
class DB_Abstract: # DB Connection constructor # INPUT: database information per db implementation (connection info / file path / windows registry / whatever # OUTPUT: N/A # DESC: constructs the db connection instance and prepares everything necessary to start actively working against the db. if db stru...
989,941
fe87c56d64011db1b61a65c3f1fea1fb80d5a821
my_str=input("What do you want to get displayed:") print(my_str)
989,942
0a4ca657a1fec0527e286fa3dbed80a67a04c3b8
#!/usr/local/anaconda/bin/python ''' A tool to calculate the fluxes from DSMACC D.Ellis 2016 ''' #functions global specs,reactants xlen = lambda x: xrange(len(x)) import numpy as np import pandas as pd import sys,os,re,multiprocessing,netCDF4 from netCDF4 import Dataset import matplotlib.pyplot as plt #netcdf fil...
989,943
1c230da8800c7a69127915ebd0c5d50afa4f8579
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Array elements swap helper. ''' import random import logging log = logging.getLogger(__name__) def swap(a, b, ind): ''' The function swaps elements of a and b on the indices stored in ind. Args: a: list of elements b: list of elemen...
989,944
82c5f9f34f493044a6e06672935e87dabeae4aa1
from flask import Flask, render_template from flask import request as req import requests app = Flask(__name__) # Root path (static) @app.route("/") @app.route("/index") def index(): return render_template('index.html') # Render a table of chemicals reachable from a start chemical by querying the # biochem4j....
989,945
70529800b7b1672ee90bbb4b45bc9e8e1b21b55b
# !/usr/bin/env python # coding=utf-8 """ Demo to integrate an ODE for ChE 344; A <--> 3B + C, membrane reactor with pressure drop, B diffusing out the membrane references: https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html https://scipy.github.io/old-wiki/pages/Cookbook/CoupledS...
989,946
6ab24ecb6bd5c51275ef2c2a8ca922bca82cc9e5
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.neural_network import MLPClassifier from sklearn.metrics import classification_report,confusion_matrix,accuracy_score import pickle wine = pd.read_csv('wine.data', names = ["Cultivator...
989,947
63f24182cf510d5b4f12d8f8dfa4eb46835fe096
#%% # 所有的数据分为一下几类: # 诊断复杂,中有数字,形容描述 如 0013 # import jieba import matplotlib.pyplot as plt import numpy as np from gensim import corpora, models, similarities from sklearn.cluster import KMeans from sklearn.externals import joblib import cla def getsample( filename , featurestr,loopnumber): fo = open(filenam...
989,948
af7dee274e05f33cb108ce4e042a4d656b2f12ba
# This is our super (parent) class. All other characers, will be subclasses of this class class Character(object): def __init__(self,name,health,power): self.name = name self.health = health self.power = power def take_damage(self,amount_of_damage): self.health -= amount_of_damage def get_health(self): ret...
989,949
8b62c09ec372d608c27dc367cd8b8597af832581
# Easy # # In a array A of size 2N, there are N+1 unique elements, and exactly one of # these elements is repeated N times. # # Return the element repeated N times. # # Example 1: # # Input: [1,2,3,3] # Output: 3 # # Example 2: # # Input: [2,1,2,5,3,2] # Output: 2 # # Example 3: # # Input: [5,1,5,2,5,3,5,4] # Output: 5...
989,950
51bafe5ea779cf950cee6d8ba08399a8345ad1aa
import cv2 from ..utils.utils import intdetector, str2bool, stringdetector def resize(img, ratio=100, size=None, interpolation=None): """ This function retrieves the image sent by the user resized with the ratio or the size inputted by the user. The ratio has priority over the size in case that it...
989,951
1f199b3c41c0a29e59a7207bb35ef9c1fff13830
# Created by [Yuexiong Ding] at 2018/2/12 # 归一化数据 # import pandas as pd import numpy as np # 原始数据集索引文件地址 INDEX_FILE_PATH = r'D:\MyProjects\TianChi\Astronomy\DataSet\RawData\train_index.csv' # 原始数据集文件存放地址 DATA_FILE_PATH = r'D:\MyProjects\TianChi\Astronomy\DataSet\RawData\TrainingData' # 采样数据文件存放根目录 SAMPLE_ROOT_PATH = ...
989,952
ee21f80715923909b6219b8681c73938587eb032
""" python的参数转换器 """ from flask import Flask from werkzeug.routing import BaseConverter app = Flask(__name__) # 1. 定义自定义的转换器 class RegexConverter(BaseConverter): """自定义转换器,用于处理参数和接收参数""" def __init__(self, url_map, regex): # 第二个参数,是flask初始化此转换器传递的,第三个是自定义的路由规则传递进来的 # 调用父类的初始化方法 super(Regex...
989,953
cadb3f74103c4285ff20edfe4c210e47fc51d4d7
# window parameters icon_name = 'car.ico' size = (1050, 600) title = 'Car Shop App' path_img = 'images/' # toolbar icons file_img = 'file.png' save_img = 'save.png' home_img = 'home.png' search_img = 'search.png' print_img = 'print.png' ID_BUTTON = 100 # database connection host = 'localhost' user ='nadya' passwor...
989,954
a4fbee525c647514a93c7cf53dfadf02693ee192
from lxml import etree import sys import re if(len(sys.argv) > 2): input_filename = sys.argv[1] output_name = sys.argv[2] else: print "Usage: python remove_unwanted_spaces.py <input harem> <output file>" sys.exit() tree = etree.parse(input_filename) for ps in tree.iterfind('//P'): inside_ps = etree.tostring...
989,955
e9ff762ce44e23422a102b4d4bbff9a6940b80e1
from pathlib import Path from mock import ANY, Mock, patch from ruamel.yaml import YAML from dwalk.cli import CLI def test_args() -> None: assert not CLI().args.include_meta assert not CLI().args.version def test_args__version() -> None: assert CLI(["--version"]).args.version @patch("dwalk.cli.CLI.p...
989,956
2d18fca1b2379676fd96c9f980d7287e90b5b3ec
#!/usr/bin/python import numpy as np import itertools as it from typing import Iterable from collections import Counter from sage.arith.functions import LCM_list import warnings import re import matplotlib.pyplot as plt import inspect # 9.11 (9.8) # 9.15 (9.9) PLOTS_DIR = "plots" class CableSummand(): def __init...
989,957
fb5b69d6bd1699377d65ce0b0b8c241373abd612
import os from colander import SchemaNode, MappingSchema from deform import FileData, Form, ValidationFailure from deform.widget import FileUploadWidget from pyramid.httpexceptions import HTTPFound from pyramid.i18n import TranslationStringFactory from pyramid.security import remember, forget from pyramid.view import ...
989,958
b8d9a96f3a3c15e81486e3d370ef16a746d964b3
# we use break to stop a loop for item in ["balloons", "flowers", "sugar", "watermelons"]: if item != "sugar": print("We want sugar not " + item) else: print("Found the sugar") break # Output: """ We want sugar not balloons We want sugar not flowers Found the sugar """
989,959
bbb5b3625278ee3020c439cf6ca49761a724b9e5
import sqlite3 from sqlite3 import Error import os import pandas as pd import json from flask import jsonify db_path = os.path.abspath('../data/testdb.db') sql = " INSERT INTO frequent_browsers \ SELECT personID, COUNT(personID) AS num_sites_visited FROM visits \ LEFT JOIN sites ON sites.id=visits....
989,960
1e8ed3f02def00383d3aae174426823f35c5847f
#strftime method is used to convert datetime as string format from datetime import datetime timestamp=1528797322 date_time=datetime.fromtimestamp(timestamp) print("date and time: ", date_time) d=date_time.strftime("%m/%d/%Y, %H:%M:%S") print("Output 2:", d) d=date_time.strftime("%d %b, %Y") print("Output 3:", d) d=da...
989,961
2c94d2c2ed45b6180c1831397686be0b0a071ea0
#!/usr/bin/python import os import requests import bitly_api import blower import tweet import twilio_sms from log import log_job from rq import Queue from worker import conn from datetime import datetime from pytz import timezone tz = timezone('US/Pacific') price_target = 35 earliest = 8 latest = 23 _blower = False ...
989,962
4c1ee3275d87bc28538e0c810e0aa2fe85cb3457
print("Bitoperatoren") a = 6 b = 7 print("a = {:04b}".format(a)) print("b = {:04b}".format(b)) print() print("a & b = {:04b}".format(a & b)) # AND print("a | b = {:04b}".format(a | b)) # OR print("a ^ b = {:04b}".format(a ^ b)) # XOR print() # NOT print("~a = {:04b} (Ausgabe mit Vorzeichen!)".format(~a)) # gi...
989,963
2b433b97e0f52db77b44bba37a1f10f3d57e72af
# Copyright 2018 DeepMind Technologies Limited. # # 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 ag...
989,964
ac8c6bb318ef8c37f3a5ccf6f3e150ae862237f3
# Critter Caretaker # Virtual pet to care for class Critter(object): """A virtual pet""" def __init__(self,name,hunger=0,boredom=0): self.name = name self.hunger = hunger self.boredom = boredom def __pass_time(self): self.hunger+=1 self.boredom+=1 ...
989,965
3b10841758f98f911670fe11abf80d86ab204f12
from sklearn import datasets import matplotlib.pyplot as plt import matplotlib.cm as cm import pandas as pd import numpy as np from sklearn.cluster import KMeans from sklearn.metrics import silhouette_samples, silhouette_score random_state = 100 blobs = datasets.make_blobs( n_samples = 500, n_features = 1...
989,966
07ab8719677ee2597ba4a27977bdbcc72aafbef8
"""Extension of app JSON capabilities.""" import flask import pytest from flask_mongoengine import MongoEngine from flask_mongoengine.json import use_json_provider @pytest.fixture() def extended_db(app): """Provider config fixture.""" if use_json_provider(): app.json_provider_class = DummyProvider ...
989,967
72fedf1334ecd62c78b8f32b35a22421cf06b69a
from PyQt5.QtGui import QIntValidator, QDoubleValidator from PyQt5.QtWidgets import QLineEdit def set_validator(edit: QLineEdit, type: str): validator = None if type == 'int': validator = QIntValidator() elif type == 'float': validator = QDoubleValidator() edit.setValidator(validator)
989,968
6447f591bed4cc660a8d12eaa32dfb4202b4e11a
import twitter import json from collections import Counter from prettytable import PrettyTable from bs4 import BeautifulSoup import requests seen = {} ### https://github.com/edsu/shortpipe/blob/master/shortpipe def unshorten(url): url = url.strip() if url in seen: return seen[url] new_url = url ...
989,969
de9a6532c93f86a3a38b0411cb18e3c1e4b758ed
from django.apps import AppConfig class Practica1Config(AppConfig): name = 'Practica'
989,970
5e35f7e3ce871d63864976b17b149d20f4afde78
from flask import Blueprint,render_template,request,url_for,redirect from app.trade_form import REGIONBForm trade_bp = Blueprint('trade_bp',__name__, template_folder='templates', url_prefix='/trade') from run import application from app import trade_util from app.trade_util import TradeUtil logger=application.config['l...
989,971
28dc1d1fb626cc1265e618e036c8ea34863a993b
# Generated by Django 3.1.7 on 2021-04-30 12:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('case_app', '0004_auto_20210424_0508'), ] operations = [ migrations.AlterField( model_name='case', name='contribute_c...
989,972
e2beb5e069669024dc51cc4852d4c049fc3307a4
# Generated by Django 3.1.2 on 2020-11-21 14:09 from django.db import migrations, models import django_cryptography.fields class Migration(migrations.Migration): dependencies = [ ('shop', '0005_auto_20201121_1528'), ] operations = [ migrations.AlterField( model_name='card', ...
989,973
a2135f2a95fc657cd8cde78ced3b321670746665
import io #stdio archivo = open("arch.txt","r") archivo.seek(5)#se situa en el caracter de una linea lineas = archivo.read() print (lineas) import pickle lista = [1,2,"hola",["holanda"]] fichero = open("archivo.pckl","wb") pickle.dump(lista,fichero) fichero.close() fichero = open("archivo.pckl","rb") data = pickle.loa...
989,974
0a9f30f0b2c886e0fcec5b7117c06ff44b8c507d
import numpy as np import cv2 image =cv2.imread("/../images/plant.jpg",-1) image.shape #getTickCount() returns number of clock count #getTickFrequency() return number of clock-cycles per second. start_time = cv2.getTickCount() for i in range(1,50,2): cv2.medianBlur(image,i) print((cv2.getTickCount()-start_time)...
989,975
ba6e7d5ba2a0182661dc26f06c51af5b4d2df1db
import pyeccodes.accessors as _ def load(h): h.add(_.Constant('GRIBEXSection1Problem', (52 - _.Get('section1Length')))) _.Template('grib1/mars_labeling.def').load(h) h.add(_.Constant('operStream', "oper")) h.alias('mars.stream', 'operStream') h.add(_.Unsigned('band', 1)) h.alias('mars.obstype...
989,976
c9dcba07b5d79de8c5321375607714c08bf17f8d
import numpy as np import unittest from flare.common.error_handling import LastExpError from flare.common.replay_buffer import Experience from flare.common.replay_buffer import ReplayBuffer, NoReplacementQueue, Sample class TestNoReplacementQueue(unittest.TestCase): @classmethod def is_episode_end(cls, t): ...
989,977
cf4d8e3043fdc1040bbb3a3baa9c8fda7b829f2d
def main(): qtd_testes = int(input()) for i in range(qtd_testes): #input só para atender o formato da entrada input() #Recebe a linha, faz split e converte cada itens do split em Int() alunos = [int(i) for i in input().split(' ')] #Atribue a alunos_desc os alunos ordenados descrecente. alunos_desc = so...
989,978
4bc18daa0b696bbb46993aa65a4944c1f8b6df1b
from bs4 import BeautifulSoup import urllib3 import socket, threading from HtmlParse import * from Server import * s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', 1911)) s.listen(10) lock = threading.Lock() while True: (client_sock, clien...
989,979
4a956c80d5a18918cd3d0564eeabfc71a6447074
""" Neural networks """ from pathlib import Path import pytorch_lightning as pl import torch import torchvision.transforms as transforms from torch.utils.data import DataLoader, Subset from torchvision.datasets import MNIST from .nopeek_loss import NoPeekLoss class SplitNN(pl.LightningModule): def __init__(self...
989,980
c75b47c5bb9a7717580a87b8d634824ba768abfb
from deuces.deuces import Card, Evaluator, Deck evaluator = Evaluator() def str2cards(s): """Parse a string like 'as8sqdtc3d3c' to a simple (flat) list of deuces card objects (in reality integers). """ assert len(s) % 2 == 0 str_list = [] cards = [] for cardnum in range(len(s) / 2): ...
989,981
c4b754d4d4f2c5bb83878c136b240072f2144989
import pytest class TransportPacket: def __init__(self, data): self.raw = data def display(self): readable = '' for byte in self.raw: print(hex(byte), end=' ') print() def is_sync(self): return self.raw[0] == 0x47
989,982
7d30405de22dd3aef980b9252207216895ca209e
S = input() N = len(S) flag = [0,0,0] if S=="".join(reversed(list(S))): flag[0]=1 if S[:int((N-1)/2)]=="".join(reversed(list(S[:int((N-1)/2)]))): flag[1]=1 if S[int((N+3)/2)-1:]=="".join(reversed(list(S[int((N+3)/2)-1:]))): flag[2]=1 print("Yes" if flag==[1,1,1] else "No")
989,983
6692ad9a42422bcf12a9a85b932e58f48d55680f
import micropython import xbee import uio import uos from umqtt.simple import MQTTClient from sys import stdin, stdout import network import machine import json import time import utime import sys import gc from sites.siteFile import pubTopic SERVER = pubTopic.server_Address msg_Topic = pubTopic.MESS...
989,984
9299db17621431e56bd0a40cace8702a8bd4dfa8
def remove_dups(lst): result=[] for x in lst: if x not in result: result.append(x) return(result)
989,985
b9bf8ea7a871d7380860f6f661c42ffe2f338303
import random import sys from host import GO def readInput(n, path="input.txt"): with open(path, 'r') as f: lines = f.readlines() piece_type = int(lines[0]) previous_board = [[int(x) for x in line.rstrip('\n')] for line in lines[1:n+1]] board = [[int(x) for x in line.rstrip('\n')]...
989,986
86a6b7bc2d3bc5a8de16f7060627cef33e3dfa6f
class Shout(object): def __init__(self, text): self.text = text def _repr_html_(self): return "<h1>" + self.text + "</h1>"
989,987
2b4e9d6953b6a3dd1e085b509434ca1fccfb7726
N = int(input()) a = [int(i) for i in input().split()] x = int(input()) ans = "NO" for i in range(N): if a[i] == x: ans = "YES" print(ans)
989,988
8338974335408fcd90d697841117c838d6a58fb2
#!/usr/bin/env python #3.6 import argparse import random import struct import sys import Queue print(sys.version) import rospy import subprocess import baxter_interface from baxter_interface import CHECK_VERSION import ikpy import numpy as np from ikpy import plot_utils from ikpy.chain import Chain from ikpy.li...
989,989
c75e8da258728bd432a040895ad0ed62b6b1e7bc
import sqlite3 conn = sqlite3.connect('meeting.db') c = conn.cursor() #search by project_name or meeting_date while 1: n = int(input('\n1.Search by project name\n2.Search by meeting date\n3.Quit searching\n\nYour choice : ')) if n==1: name = input('\nEnter project name : ') c.execute("select * from meet...
989,990
efc31df5a8f55a7d2d6a67d47bde5326e500abba
"""AD5272 - device access class for the AD5272 I2C potentiometer Provides access to control the wiper positions for the AD5272 device with helper methods to set potential differences and resistances in potential divider and rheostat mode respectively. Adam Davis, STFC Application Engineering Group. """ from i2c_devi...
989,991
a508362865a1a4268d17eda17be176ebf3dce5ad
from django import forms from .models import GrievanceForm, ApplicationStatus class StudentHomeViewForm(forms.ModelForm): class Meta: model = GrievanceForm fields = ('document1', 'document2', 'document3', 'document4', 'document5', 'preferedStation1', 'preferedStation2', 'preferedStatio...
989,992
387b0ed278b0fef3c0a5953227cf6d16534ddbf0
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """NowcastingPlus is a basic model for short-term forecasting. This modules contains class NowcastingParams, which is the class parameter a...
989,993
1b9910e3702965de1588a604022ba1064cd00bc3
_ = input().split(' ') my_list = ([int(i) for i in input().split(' ')]) first_set = set([int(i) for i in input().split(' ')]) second_set = set([int(i) for i in input().split(' ')]) p = 0 for i in my_list: if i in first_set: p += 1 if i in second_set: p -= 1 print(p)
989,994
52d67cc8967c1e37ed4d4a5a12401e55132c04ce
# Generated by Django 3.1.1 on 2021-01-04 09:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('overview', '0004_auto_20210104_1707'), ] operations = [ migrations.CreateModel( name='host_notmonitor', fields=[ ...
989,995
7308465ba85622d1a362a13ed986bade61705c17
import reversion from django.utils.timezone import now from rest_framework import status from rest_framework.reverse import reverse from reversion.models import Version from datahub.company.constants import BusinessTypeConstant from datahub.company.models import Company from datahub.company.test.factories import Compa...
989,996
0b910a2daaa7b40f477c2c00a0756ce18305e2b2
import secrets import string import typing import jwt class InvalidToken(Exception): pass def generate_jwt_token(secret: str) -> str: encoded_jwt = jwt.encode({"usage": "authentication"}, secret, algorithm="HS256") return encoded_jwt.decode("utf-8") def validate_jwt_token(token: str, secret: str) -> ...
989,997
4d05fe08e21c2ce181eca2efd2ad5bec0fc2aaba
from django.conf.urls import include, url from django.contrib import admin import pollsapi.views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^polls/$', pollsapi.views.PollList.as_view()), url(r'polls/(?P<pk>[0-9]+)/$', pollsapi.views.PollDetail.as_view()), url(r'^create_user/$', ...
989,998
448711ec340d75176fea03ea2cb39132fd373ec3
print("안녕하세요?") print("programming에 입문하신 것을 축하드립니다.")
989,999
39f8928e22c9ceb08719a3fdbb7353a776c2acac
import pytest from plotboss.plotlog import PlotLogParser from datetime import datetime import pendulum def test_log_parser(): p = PlotLogParser() p.buffer = 0 p.size = 0 p.buckets = 0 p.num_threads = 0 assert p.size == 0 assert p.buffer == 0 assert p.buckets == 0 assert p.num_thread...