index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
991,300 | a376bd4c51f14aa15a5c54c3dd345defdfddd19c | from sensible_raw.loaders import loader
from world_viewer.cns_world import CNSWorld
from world_viewer.glasses import Glasses
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
from matplotlib.colors import LogNorm
from sklearn.utils import shuffle
folder = "tmp/Shuffled/"
# l... |
991,301 | f36e4d14294158bcf9552917f7e2e915c8ece6a6 | """try:
numero1 = 5
numero2 = 3
div = numero1 / numero2
print(div)
except ZeroDivisionError:
print("No puedes dividir por cero")
except:
print("Ha ocurrido un error")
else:
print("La division funciono correctamente") # cuando funciona
finally:
print("Estamos aprendiendo excepctiones") # ... |
991,302 | 566f45891887730a86a75384232bd8e69c1cc479 | import socket, time, persistqueue, os, shutil, collections, threading
quit = False
def delete (q): # время жизни сообщений(высчитываю не совсем корректно но это бетка)
try:
time.sleep(0.2) # чтобы меньше лагало
clock = time.strftime("%d%M%S", time.localtime()) # время сейчас
clock = int(clock)
i = q.qsiz... |
991,303 | e3905813c7065f41e7ebfd67f3d74686198e84b8 |
import re
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import csv
import time
options = Options()
options.add_argument("--headless")
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')
options.add_argument("start-maximized")
options.add_argument("disab... |
991,304 | 4418a09c9b54546615419d64e10c23a4eafe4156 | """This is a module of utils."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
|
991,305 | 901a4bcf1d6c0ebab5018b7a30d7d43b8c84db3f | """
Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.
For example, with A = "abcd" and B = "cdabcdab".
Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A r... |
991,306 | 18bfe9b908b234df31b7fb5af163fdb15bde8901 | #SConstruct
SConscript('SConscript',variant_dir='build',src='.',duplicate=0)
|
991,307 | 78385938cc460a43098676071d24b41b37d61d1e | # Main driver for the Aperture cli.
# docopt uses the below docstring to describe the Aperture interface
'''
Aperture
Usage:
aperture <input>... [options]
Options:
-o <opath>, --outpath <opath> Output location for the processed images.
-q <qual>, --quality <qual> Quality level applied to each image. ... |
991,308 | 6dc286d31e6e540ae7827820fe76e7bf9148e59f | # encoding: utf8
import re
def parse_oss_url(url):
pattern = re.compile(r'(http|https)://([a-zA-Z0-9_-]+)\.(.*?)\/(.*)')
match = pattern.match(url)
if match:
return match.groups()
else:
raise Exception('Invalid OSS url')
|
991,309 | 22375c1f5d596b6547a12a59596d984168afc5a3 | # Generated by Django 2.0.3 on 2020-07-21 20:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stocks', '0003_auto_20200721_1547'),
]
operations = [
migrations.AddField(
model_name='saved_stock',
name='ticker',
... |
991,310 | e06800cf168048529e759c18590c3c0f03f9cd54 | class Current:
def constant_current(self):
print("Enter the magnitude of current ")
self.current= float(input())
if not isinstance(self.current,float):
raise TypeError("NOT A NUMBER")
else:
return self.current
def step_current... |
991,311 | 12ae65e17cae5e608a067b8379b47822502791c9 | #!/usr/bin/python
#encoding=utf8
import requests,re,datetime,time
import sys
reload(sys)
sys.setdefaultencoding('utf8')
#备份当前的策略 一天前
bakuptime = 1
#删除策略 三天前
deletetime = 3
def Find_indexs(url):
res = requests.get(url).text
indexs_list = [i.split()[2] for i in res.split("\n") if i]
#print(indexs_list)
#找出匹配符合的索引... |
991,312 | e5a8251c158971aa3f33aeacda635d222ddd7b2a | # _*_ coding:utf-8 _*_
import pymysql
conn = pymysql.Connect(host="127.0.0.1", port=3306, user="hujiaming", passwd="123456", db="xgyw_cc", charset="utf8")
cur = conn.cursor()
start_url = "http://www.xgyw.cc"
little_item_sql = "insert into little_item values"
def combine_insert_sql(table_name, id, name, url):
ins... |
991,313 | 7db8cc8ef1ee16142a4afc1570c974b3ff2fc98f | # Reading and writing files
# we will use functions to make a simple text editor
from sys import argv
script, filename = argv
print "We're going to erase %r" % filename
print "If you don't want that, press ctrl + c(^C)"
print "If you want that, press return"
raw_input("?")
print "Opening the file..."
... |
991,314 | 86527daa40310becf11261ecd57e7b0a6d04dcd3 | from conans import ConanFile, CMake, tools
import os
package_version = "1.2.1"
channel = os.getenv("CONAN_CHANNEL", "testing")
username = os.getenv("CONAN_USERNAME", "marcokoch")
class LibunwindTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "libunwind/%s@%s/%s" % (package... |
991,315 | 4faf40030ca73a5f357334cbb5d4a6bd0d96398a | #Django
from django.urls import path
#Django rest framework
from rest_framework.urlpatterns import format_suffix_patterns
#Views
from users_manage_api import views as user_views
"""In order to handle urls management better, the "views" name has been changed"""
urlpatterns = [
path('login/', user_views.UserAPIView... |
991,316 | 78a7dc7c4ef3bd3564f3134afd4e539c98c55636 | from flask_jwt_extended import get_jwt_identity
from core.kube import models
class DeploymentCreatorFilter:
@classmethod
def as_filter(self, *args, **kwargs):
user = get_jwt_identity()
return user and models.Deployment.creator_id == user['id'] |
991,317 | 5c19f017ea1a8d483aeb0ce1fead98ba153222ed | #Charles Fee
#I pledge my honor that I have abided by the Stevens Honor System
# nim template DNaumann (2018), for assignment nim_hw11.txt
# Global variables used by several functions
piles = [] # list containing the current pile amounts
num_piles = 0 # number of piles, which should equal len(pile)
def... |
991,318 | 77464686c0e31285780d0194580066a0dc0c9bc8 | from datetime import date
from clld.tests.util import TestWithEnv, XmlResponse
class OaiPmhResponse(XmlResponse):
ns = 'http://www.openarchives.org/OAI/2.0/'
@property
def error(self):
e = self.findall('error')
if e:
return e[0].get('code')
def test_ResumptionToken():
f... |
991,319 | 650725dd6cfc5e53884ac3a1ee649d0f0674bb6b | # coding: utf-8
from girlfriend.tools.code_template.workflow_template import PluginCodeMeta
all_meta = {
# csv series
"read_csv": PluginCodeMeta(
plugin_name="read_csv",
args_template="""[
CSVR(
path="filepath",
record_handler=None,
... |
991,320 | e03df16c8ee2f5bf8e8b5cb038c3144a5663d8dd | from parapy.core import *
from parapy.geom import *
class RudderEx(Base):
@Attribute
def pts1(self):
return [Point(1, 1),
Point(1, -1),
Point(-1, -1),
Point(-1, 1),
Point(1, 1)]
@Part
def quad1(self):
return PolygonalFace... |
991,321 | 4a3d29f3b48fc0228e6c4df48e36993070f98fb5 | import datetime
import xlrd
import pymssql
from tables_results import TableCollection
class nstr:
def __init__(self, data):
self.data = str(data)
def __str__(self):
return self.data
class datetime_str:
def __init__(self, data):
if isinstance(data, float):
self.data ... |
991,322 | 30828dca5ae041bb4d41deef96a0aaa238bbba4b | import requests
from bs4 import BeautifulSoup
import pymysql
from re import sub
# b5647ade0475c5
# 40d209f8
# us-cdbr-east-02.cleardb.com
# heroku_56d2d16ef2b2e35
# db = pymysql.connect("us-cdbr-east-02.cleardb.com","badaadfc741319","fd67aae8","heroku_64a98996a6e263e", charset='utf8')
db = pymysql.connect("localhost","... |
991,323 | 69d1cbd3391f0df19a35c18a9face9e5ee15305f | ghana_geometry = """{
"country": {
"name": "Ghana",
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[-0.553262, 5.365266],
[-0.6399, 5.32782],
[-0.726983, 5.298418],
[-0.727129, 5.285019],
[-0.747849, 5.274265... |
991,324 | f37b149c735023347a5bea770bbf12f4e8f1901f | #!/mcms/python/bin/python
# For list of profiles look at RunTest.sh
#*PROCESSES_PROFILE_FOR_SCRIPT=Profile_1
#*export MPL_SIM_FILE="VersionCfg/MPL_SIM_1_WITHOUT_RTM.XML"
from McmsConnection import *
from ContentFunctions import *
from HotSwapUtils import *
import string
#--------------------------------------------... |
991,325 | 2555c7d46f635f12162185b86539ca92114e9645 | var1=100
if var1:
print("something")
print(var1)
var2=13
if var2:
print("your")
print(var2)
print("good bye") |
991,326 | 55855258c7023721cf17dfd714796c89ac2cca1a | from .models import *
from rest_framework import viewsets
from django.shortcuts import render
from .serializers import ProdutoSerializers
from django.core import paginator
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
class ProdutoViewSet(viewsets.ModelViewSet):
queryset = product.objec... |
991,327 | f20d26b1168b29f5b1ff621bd7c93eeb90a0a38f | """
Project.x
Author: Michael Redmond
"""
from __future__ import print_function, absolute_import
from ._actions import Actions, Commands
|
991,328 | 3b8ec3081e80996d4d74c8778099918a944803de | # -*- coding:utf-8 -*-
import requests
import time
import random
from multiprocessing import Pool
from bs4 import BeautifulSoup
import codecs
#中文分词工具结巴
#import jieba
def LoadUserAgent(uafile):
uas = []
with open(uafile, 'rb') as uaf:
for ua in uaf.readlines():
if ua:
uas.app... |
991,329 | edf1e0c7e302aa361638b815a0c18e131c83e757 | from collections import deque
import numpy as np
import random
from gym_minigrid.minigrid import *
from gym_minigrid.envs.grid_rooms import GridRooms
from gym_minigrid.register import register
MOVE_VEC = [
np.array([-1, 0]),
np.array([0, -1]),
np.array([1, 0]),
np.array([0, 1]),
]
def connect_rooms(... |
991,330 | 2110e66bb69069cb5a9ed90bb9697b0f18e48af3 | import os
import unittest
import json
from flask_sqlalchemy import SQLAlchemy
from flaskr import create_app
from models import setup_db,Question, Category
class TriviaAppTestCase(unittest.TestCase):
"""This class represents the trivia test case"""
def setUp(self):
"""Define test variables and initia... |
991,331 | 014c55d7624ee3dd324b7d5418c661dbe54587d6 | #!/usr/bin/env python3
# articles_scraper.py
import asyncio
import json
import logging
import re
import sys
import time
import aiohttp
from aiohttp import ClientSession
from bs4 import BeautifulSoup
from pathlib import Path
import aiomysql
logging.basicConfig(
format="%(asctime)s %(levelname)s:%(name)s: %(messa... |
991,332 | 952d4e3a972c27fd6ec45f40d876e10f7bfd41eb | from django.db import models
from django.contrib.auth.models import User
from datetime import date
from django.forms import ModelForm
from django import forms
# Create your models here.
class Genre(models.Model):
"""Model representing a book genre."""
name = models.CharField(max_length=200, help_text='Enter a... |
991,333 | 99aea987557331db056e21b5139dd71ac51b4268 | # users/urls.py
from django.conf.urls import url
from dashboard.views import CreateOrganisation
from dashboard.views import OrganisationAPIView
urlpatterns = [
url(r'^$', CreateOrganisation.as_view()),
url('search/', OrganisationAPIView.as_view())
] |
991,334 | cffbb7bf9591fd2dfc3b9d9e161779d4316dbd28 | from lambdastack_lex import lexer
from lambdastack_interp_gram import parser
from lambdastack_state import state
from lambdastack_interp_walk import walk
from grammar_stuff import dump_AST
def main():
while True:
try:
input_stream = input()
except EOFError:
return
# initialize the state object
stat... |
991,335 | d2c34d45097c8829c7222fbd290b35888560e830 | def show_info(name):
print('이름:', name)
#show_info('홍길동') # 이렇게 해버리면 import될때 자동으로 실행되어버린다
if __name__ == '__main__': # 이렇게 해야 python module3.py같이 밖에서 직접 실행할때만 실행되고 import될때는 실행되지않는다
show_info('홍길동') |
991,336 | 9641c6a496a68af3743f177d3eaef02a63336c60 | from pylab import *
delta = 0.01
x = arange(-3.0, 3.0, delta)
y = arange(-3.0, 3.0, delta)
X,Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2 - Z1 # difference of Gaussians
cmap = cm.get_cmap('rainbow', 10) # PiYG
cmap_colors = cmap._segmentdata
... |
991,337 | bd8fc248544a10327c03f02d0399604a27e2e1c3 |
import requests
# Loop over a file using the hint commend
for line in open("ELECTION_ID"):
# Download the csv
addr = "http://historical.elections.virginia.gov/elections/download/{}/precincts_include:0/".format(line[5:10])
resp = requests.get(addr)
# Set the format of name groups, it will show up election by e... |
991,338 | 063944aad9553afb016e2a2f97d1e68f78dccc04 | import gym
import numpy as np
import random
import matplotlib.pyplot as plt
import math
from collections import deque
import tensorflow as tf
import tensorflow_quantum as tfq
import cirq
import sympy
import time
import datetime # https://stackoverflow.com/questions/10607688/how-to-create-a-file-name-with-the-current-d... |
991,339 | 2a7e99b0995e896b97c9862990e9785b45343f7f | from django.db import models
from django.db.models import Q, QuerySet, F
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from collective_blog import settings
from collective_blog.utils.errors import PermissionCheckFailed
from s_markdown.models import MarkdownField, HtmlCacheF... |
991,340 | 1f94005e306b8d4827fd23377469105a9ddb3250 | import unittest
from osu.local.beatmap.beatmapIO import BeatmapIO
from analysis.osu.std.map_data import StdMapData
from analysis.osu.std.map_patterns import StdMapPatterns
class TestStdMapPatterns(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.beatmap = BeatmapIO.open_beatmap('unit_test... |
991,341 | b350f7e361c25d5acb106c29d759d89b0fe1f002 | from bisect import bisect_left
import WhiteListData, BlackListData
import re
class WhiteList:
def __init__(self, sequenceList=[]):
self.setChatType(0)
self.setSequenceList(sequenceList)
def setChatType(self, chatType):
if chatType == 0:
self.setWords(WhiteListData.WHITELIS... |
991,342 | 6ff8d7d416a22a5153597aafd48800715be7f4dc | from itertools import zip_longest
def chunk(n, iterable, fillvalue=None):
'''
Generate sequences of `chunk_size` elements from `iterable`.
source: stackoverflow, 8991506
Usage:
grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
'''
args = [iter(iterable)] * n
return zip_longest(fillvalue=fi... |
991,343 | 90bac200c066fbfdd9194de7d3b0aae1b6bfa430 | import argparse
from datetime import datetime,timedelta
import glob
import json
import logging.config
import os
import pprint
import re
import shlex
import signal
import subprocess
import sys
import time
import requests
requests.packages.urllib3.disable_warnings()
from sysmon_more import SysMonMore
from configparser ... |
991,344 | 0a8dbeae3d3320b132c5827a28f8eabef4f9a42e | from flask_restful import Resource
from flask_login import login_required,current_user
from flask import request
from .models import Post
from app import db
class Index(Resource):
def get(self):
return {"message":"Hello World"}
class Article(Resource):
decorators = [login_required]
def post(self):
... |
991,345 | cb9a55072ccfd0257e7f2e81ab10e1d00d64dbd0 | ''' this is the module that consumes assumption files and process the raw input'''
class Assumptions():
def __init__(self, assumption_filename):
self.assumption_filename = assumption_filename
def mortality(self):
"""return a class of mortality curve object"""
pass
def lapse(self)... |
991,346 | 6907bff43fa8e3f0dc23eced4c684a496d76ed89 | #!/home/antounes/anaconda3/bin/python3
#-*- coding: Utf-8 -*-
# Algorithme d'exponentiation rapide
# Etant donnés un réel positif a et un entier n, on remarque que :
# a^n =
# (a^(n/2))^2 si n est pair,
# a*(a^(n-1)/2)^2 si n est impair.
# Cet algorithme se programme naturellement par une fonction récursiv... |
991,347 | 6d04c140172fcf20fe19b3796395dad01c362b56 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : quickstart_demo0.py
@Time : 2020/10/29 15:25:16
@Author : Jeffrey Wang
@Version : 1.0
@Contact : shwangjj@163.com
@Desc : 官方QuickStart第1个策略示例
买入的尝试,如果价格连续跌两天则买入,如果持仓5天则卖出
加入手续费的概念
'''
import backtrader as bt
import bc_study.tushare_csv... |
991,348 | 26ff9ccf035c6dd70c114584b282ec9cf03644d2 | #!/usr/bin/env python
import ast
import pickle
import pprint
import os
import os.path
import random
import string
import sys
import numpy as np
from scipy.io import savemat, loadmat
from skimage.io import imread, imsave
import skimage.measure
import skimage.segmentation
#############################################... |
991,349 | 40fa7e4fe59d3b6feb98a82d662b9df24e71283c | import keras
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from keras.models import Sequential
from keras.layers import Dense, Activation, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization
from keras.optimizers import Adam as Adam
from keras.layers.advanced_activations import LeakyReLU
imp... |
991,350 | b40d0505c6681e47d0823bce2ff7e8e8164b2eeb | from collections import defaultdict
from typing import List, Tuple
# Given an array of size n, find the most common and the least common elements.
# The most common element is the element that appears more than n // 2 times.
# The least common element is the element that appears fewer than other.
# You may assume that... |
991,351 | 2fc0061a2f30f746d35fdb74034dfb0e76ea2429 | # -*- coding: utf-8 -*-
"""
File Name: test02
Author : mengkai
date: 2019/2/2
description:
"""
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# 定义输入和参数
x = tf.placeholder(tf.float32, shape=(1, 2))
w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1)... |
991,352 | f6059cde4c9a0af3957d3e9724e6b13491ff7081 | def even(x):
if x % 2 == 0:
return True
else:
return False
def productnum(v, a, b, c):
if a > b:
return v
elif even(c) or c == 0 or a == b:
return productnum(v*a, a+2, b, c+1)
else:
return productnum(v*a, a, b, c+1)
def productden(v, a, b, c):
if a > b:
... |
991,353 | e01f63b91f4f98a0bb290802beaf48ef386fc418 | # import re
# n=input()#行数
# print(n.isalpha())
# print(n[len(n)-1])
# print(''.join([s for s in n if s.isalpha()]))
# for j in range(ord(n)):
# input_lines = input()
# print(input_lines)
# for each in input_lines[j]:
# print('test')
n=ord(input("输入行数:\n"))
stopword = ''
str_line = ''
for line in iter... |
991,354 | 7c383f093aa1b93f6ea2b94416beb3f3de0dae6b | from .sift import SIFT
from .cm import ColorMoments
from .hog import HOG
from .lbp import LocalBP
from .cavg import ColorAvg
MODELS = {"cm": ColorMoments, "hog": HOG, "cavg": ColorAvg}
def getSupportModel():
return list(MODELS.keys())
def creatModel(model, **kwargs):
model = model.lower()
if model in ... |
991,355 | a9aadbb5929b3de8dafbb9373ad5bf55a371df50 | # -*- coding: utf-8 -*-
from PyQt4 import QtCore
from PyQt4.QtGui import *
class Ui_Main(object):
def setupUi(self, Main):
Main.setObjectName("Main")
Main.resize(602, 402)
# CentralWidget
self.CentralWidget = QFrame(Main)
# menubar
menubar = Main.menuBar()
... |
991,356 | ea1df97cb5b3facc1547baee6e0242ad97c5d9c9 | #!/usr/bin/env python3
'''
Example exposing the plot_labelled_group_connectivity_circle function.
Author: Praveen Sripad <pravsripad@gmail.com>
'''
import numpy as np
from jumeg.connectivity import plot_labelled_group_connectivity_circle
from jumeg import get_jumeg_path
import yaml
# load the yaml grouping of Free... |
991,357 | 63da31c5aa0f658217c88218a2db63f3de96c23d | import pytest
from check_phonenumber.service import CheckPhoneNumber
@pytest.fixture
def test_data():
data = {
"phone_number": "+40721234567",
"country_code": "RO"
}
return data
def test_service(test_data):
result = CheckPhoneNumber.validate_phone(data=test_data)
assert result.get... |
991,358 | d3716c97308e6f8ae7ae4ac365e3bf621ca6956e | from .base_page import BasePage
from .locators import ProductPageLocators
class ProductPage(BasePage):
def click_on_add_to_basket_button(self):
add_to_basket_button = self.browser.find_element(*ProductPageLocators.ADD_TO_BASKET_BUTTON)
add_to_basket_button.click()
def should_be_add_basket_bu... |
991,359 | dd406f723aa18bc3a39a96b592e18230e848ee72 | '''
This module contains the necessary functionality to run
basic runtime tests. The test suite is run for all programming
languages added in `test/config.py`.
**Important**: This test suite makes several assumptions regarding
naming conventions and the location of specific files:
- The bot binary should be located... |
991,360 | 0879b90882ed24a893e6c953db1e59353a75c7ec | # Utility functions meant to aid our convolutional neural network.
from scipy import stats
import pandas as pb
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
%matplotlib inline
plt.style.use('ggplot')
def read_data(file_path):
'''
TODO: Documentatio... |
991,361 | 148df04ef59f5e2b9737af2dfa739caca0837044 | # Copyright 2020 Kaggle Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
991,362 | 1fcb3b54cede07afaf085000fa02be3e0637f1c5 | for i in range(1, 101): # 1부터 100까지 증가하면서 100번 반복
if i % 2 != 0: # i를 2로 나누었을 때 나머지가 0이 아니면 홀수
continue # 아래 코드를 실행하지 않고 건너뜀
print(i) |
991,363 | 3c724ec486afe970ddeb0fac0bed4985fbf7ee48 | from db import Icd10Code, db, Mapper, Icd9Code
import codecs
def read_icd10_codes():
# Diagnosis
with open('sources/icd10cm_order_2012.txt', 'r') as f:
for line in f.readlines():
code = line[6:13].strip()
if len(code) > 3:
code = "%s.%s" % (code[:3], code[3:])
... |
991,364 | 7f947a937baaa67619958ad31962a7019a64b5f7 | """14. Special operators
Write note on Identity operator
Write note on membership operator
"""
"""membership opetator
Membership operators are operators used to validate the membership of a value.
It test for membership in a sequence, such as strings, lists, or tuples.
in operator : The ‘in’ operator is used to c... |
991,365 | 9daab8048af84695a09365277469632ec7e49c56 | def primeFactors():
num=int(input("enter a number to find the factors:"))
for i in range(2,num):
if (num%i)==0:
print(i)
num=num/i
primeFactors() |
991,366 | 3dcf716fd35483347e4d8be090791d9d2ee09e9a | import pygame
for font in pygame.font.get_fonts():
print(font)
|
991,367 | d5975e11a3aa6600e127fd05475a44b81fb65814 | import logging
import multiprocessing
from scipy import signal
import scipy.io.wavfile
import itertools
import numpy
import gc
logger = logging.getLogger(__name__)
def remove_channel(samples):
return samples[:, 0]
def _do_filter(args):
samples, fir_window = args
filtered_samples = scipy.signal.lfilter(fi... |
991,368 | d0c63b20f88045392d232499fcb76321950a2ee0 | #
# Project: MXCuBE
# https://github.com/mxcube.
#
# This file is part of MXCuBE software.
#
# MXCuBE 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, either version 3 of the License, or
# (at your optio... |
991,369 | 6103a7e9073d77c64c8e757b927e5b33bc3abf29 | #!/usr/bin/env python
# -*- coding=utf-8; -*-
"""
Calculate monitor DPI.
"""
from math import sqrt
def dpi(x, y, diag):
return sqrt(x*x + y*y) / diag
hor_res = input('Horizontal resolution: ')
vert_res = input('Vertical resolution: ')
diag = input('Diagonal size: ')
result = dpi(hor_res, vert_res, diag)
print '... |
991,370 | d93727737a9f2cbdd1694d55f2948679d6c25b11 | from django.test import TestCase
from django.urls import reverse
class TestViews(TestCase):
def test_index(self):
response = self.client.get(reverse('index'))
self.assertContains(response, 'TDE Central')
|
991,371 | 1d1c8d7b42d0ec41355ad8400db4247a4f55f7fe | #################################################################################
# Author : Webkul Software Pvt. Ltd. (<https://webkul.com/>)
# Copyright(c): 2015-Present Webkul Software Pvt. Ltd.
# All Rights Reserved.
#
#
#
# This program is copyright property of the author mentioned above.
# You can`t redistri... |
991,372 | f96dee8db7d6e1cfc0ded654c7f1c6df483472c7 | """ https://leetcode.com/problems/reconstruct-original-digits-from-english/
The order of digits is the key to solve problem.
Go through the digits in order, and remove the letters from the string.
"""
from header import *
class Solution:
def originalDigits(self, s: str) -> str:
mp = [('zero', 'z', 0),
... |
991,373 | 1ce14ae1c9f5fc7b43a719b5d7bf5da7bb30be9e | ##Dylan Rodriguez
## TCMG 412
## Project 3 -- Python Stuff
## This uses Python 3
import urllib.request
import os.path
from os import path
import re
from collections import Counter
url = "https://s3.amazonaws.com/tcmg476/http_access_log"
#Regular expression used to parse the log file -- breaks the line into groups
... |
991,374 | 9bb4b3a3ca5137ebf8320a5d34158a33713b84d7 | """Application Framework classes to handle RGB images
"""
from rgbLib import *
|
991,375 | 8e4cec50d50eb0da92cecd78eecad4be92c22ced | import os
from os.path import basename
os.environ['CUDA_VISIBLE_DEVICES'] = ''
from keras.models import load_model
import matplotlib.pyplot as plt
from skimage import io
import numpy as np
from skimage.color import gray2rgb, label2rgb
from skimage.io import imsave
from datetime import datetime
from functions import y... |
991,376 | fea6c00133f7cee1d29806575660c595bc628f19 | import matplotlib.pyplot as plt
import numpy as np
from random import random
import matplotlib
from skimage.filters import threshold_otsu
from skimage.color import rgb2gray
import skimage.morphology as m
def FindPixel(img): #find foreground pixel image
for i in range(img.shape[0]):
for j in range(img.shape... |
991,377 | d69b447eb28fea1b3565fd138ef70b7c523297ba | from django.shortcuts import render
from django import views
from django.http import HttpResponse
# Create your views here.
class Home(views.View):
def get(self, request):
return HttpResponse('This is the home page with a GET request <h1> this is the greatest </h1>')
|
991,378 | fc0697e35593d14e8bb771ec88f37aefc8b39209 | from django.shortcuts import render
def board(request):
if request.method == "GET":
return render(request, 'index.html') |
991,379 | e31a6eaa6e72e48fe3b76c4bb4e9b6ac9b1cbbfa | # Escribe un programa que lea una cadena y devuelva un diccionario con la cantidad de apariciones de cada carácter en la cadena.
dict = {}
cadena = input("Dame una cadena:")
for caracter in cadena:
if caracter in dict:
dict[caracter]+=1
else:
dict[caracter]=1
for campo,valor in dict.items():
print (campo,"->... |
991,380 | 9df37dd72e55b3b533bb619bc9a4bb7e66aa5495 | #!/usr/bin/python
import serial, time
#initialization and open the port
#possible timeout values:
# 1. None: wait forever, block call
# 2. 0: non-blocking mode, return immediately
# 3. x, x is bigger than 0, float allowed, timeout block call
ser = serial.Serial()
#ser.port = "/dev/ttyUSB0"
ser.port = ... |
991,381 | 2fe99e90d14917c493bb1efaa074ca5dcd9ebe40 | # Jacob Wahl
# 2/8/21
# Problem 1.8 - Wrtie an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.
# -> list[list[int]]
def zeroMatrix(matrix: list[list[int]]) -> list[list[int]]:
# Not in-place
'''
new_matrix = [[-1 for y in range(len(matrix[x]))]
... |
991,382 | 91aab731235f6802cf666a8503daf4567c26aadb | from trade_tariff_reference.documents.tasks import generate_fta_document
from trade_tariff_reference.documents.utils import update_document_status
from trade_tariff_reference.schedule.models import DocumentStatus
def generate_document(agreement):
update_document_status(agreement, DocumentStatus.GENERATING)
ge... |
991,383 | 080262a299ee72f4c18ac103e7dbe0bb94ed1089 | import numpy as np
np.random.seed(2019)
np.set_printoptions(precision = 3)
x = np.random.laplace(loc=10, scale=3, size = 1000)
x[:10]
hist, bin_edges = np.histogram(x)
hist
bin_edges
# Lo que np.histogram hace para crear los intervalos
min_edge = min(x)
max_edge = x.max()
n_bins = 10
bin_edges = np.linspace(start=mi... |
991,384 | 6323af2b6111865885b15102a9bac7a225602753 | from modelo.album import Album
from modelo.cancion import Cancion
from modelo.declarative_base import session, engine, Base
from modelo.interprete import Interprete
class Coleccion():
def __init__(self):
Base.metadata.create_all(engine)
def darAlbumes(self):
albumes = session.query(Album).al... |
991,385 | 8cbfcb3c98b516f16328b10ad5eea08e3de76df3 | from wtforms import Form, SubmitField, BooleanField, TextField, SelectField, \
PasswordField, IntegerField, FieldList, FormField, HiddenField, TextAreaField, validators
from rfk.database.streaming import Relay
class RelayForm(Form):
address = TextField('Address', [validators.Required()])
port = TextField... |
991,386 | ccc4966742583eb606745195a5c2566b1222074e | """
You are given a m x n 2D grid initialized with these three possible values.
-1 - A wall or an obstacle.
0 - A gate.
INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.
Fill each empty room with the distan... |
991,387 | 416eacbf58b7faa44c69c6ae88aba485775b76a8 | from rest_framework import serializers
from exam.models import ExamSession
class ExamSessionAPISerializer(serializers.ModelSerializer):
def create(self, validated_data):
user = ExamSession.objects.create(start=validated_data['start'], finish=validated_data['finish'],
... |
991,388 | 2cfbc7a454c1c923bf8a555f036bb376940a42c7 | from standardweb import db, app
from standardweb.models import ForumCategory, ForumTopic, ForumPost
def migrate_post_topic_counts():
for category in ForumCategory.query.all():
for forum in category.forums:
post_count = 0
forum.topic_count = ForumTopic.query.filter_by(deleted=False... |
991,389 | c4436f4bf290c0c21275206d9e4dde9dd9819a4e | import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('ex.png')
kernel = np.ones((5, 5), np.uint8)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
erosion = cv2.erode(blurred, kernel, iterations=2)
#cv2.imshow("Image", erosion)
#cv2.waitKey(0)
im... |
991,390 | 6a6d12806425206c959ddebb74f4d93d5dfba2ef | '''
PYTHON SERIAL DEBUGGING CODE
HOW TO USE:
1. run script in terminal with the -i flag and with a comport number as argument (python -i main.py)
e.g. 'python -i main.py 3'
2. to continuously print recieved data, type read()
3. python will now print all received data to the console
4. to stop reading, use a keyboard... |
991,391 | 5be8585cf7bef75ebc88d583c948ba6d74aa49ed | # Generated by Django 3.0.2 on 2020-01-14 02:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('occasions', '0002_assembly_address'),
('whereabouts', '0003_address'),
]
operations = [
migrations.AddField(
model_name=... |
991,392 | 19f6e01ef5a0566fb91c672995c0458b7443645e | import random
# Read and understand the docstrings of all of the functions in detail.
def make_deck(num):
'''(int)->list of int
Returns a list of integers representing the strange deck with num ranks.
>>> deck=make_deck(13)
>>> deck
[101, 201, 301, 401, 102, 202, 302, 402, 103, 203, 303, 403... |
991,393 | 54bf3d0ebcc1fa0f13c6ee5079bc1533a571bc29 | __author__ = 'wdolowicz'
def test_add_group(app, xlsx_groups):
group = xlsx_groups
old_list = app.group.get_group_list(app.main_window)
app.group.add_new_group(app.main_window, group)
new_list = app.group.get_group_list(app.main_window)
old_list.append(group.name)
assert sorted(old_list) == so... |
991,394 | bc2797c8a35dff6ac9ca202bef68ee68152623c7 | from numpy import absolute, where
from scipy.spatial.distance import correlation
from .ALMOST_ZERO import ALMOST_ZERO
def compute_correlation_distance_between_2_1d_arrays(_1d_array_0, _1d_array_1):
correlation_distance = correlation(_1d_array_0, _1d_array_1)
return where(absolute(correlation_distance) < AL... |
991,395 | 2897778bb879464cf29b7190a2fac3468ffb0bf7 | API_KEY="675cbcc8a79998079a4605a19ccdca44"
|
991,396 | 73af06f39b5bea34eb5376cd2bc184ff625390f2 | #!/usr/bin/env python
# encoding: utf-8
"""
This is the bootstrap that installs required code at runtime
and runs the tool for the job.
The bootstrap is also responsible for communicating with the
slave daemon on the host (this is assumed to be running in
a virtual machine guest).
"""
from __future__ import absol... |
991,397 | 92ac3abee26a3fc35f22bfdbf6e6531cdf7d4ca2 | #stampa i primi 6 multipli di n
def StampaMultipli(n):
i = 1
while i <= 6:
print (n*i, '\t')
i= i + 1 #perché?
print ()
StampaMultipli(6)
#generalizzazione 6*6
def TabellaMoltiplicazioneGenerica(Grandezza):
i = 1
while i <= Grandezza:
StampaMultipli(i)
i = i + 1
#generalizzazione7*7
def Stam... |
991,398 | f95af2c6d99bb2cd827362f0266e24022a09f8a9 | from functools import wraps
def beg(target_function):
@wraps(target_function)
def wrapper(*args,**kwargs):
msg,say_please=target_function(*args,**kwargs)
if say_please:
return "{}{}".format(msg,'please ! I am poor:(')
return msg
return wrapper
@beg
def say(say_please=Fa... |
991,399 | 0ce2b98956ff98d7f5fe328170339a429baae9c4 | # coding=utf-8
# *** WARNING: this file was generated by pulumi. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import copy
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.