index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
15,400 | 0563408648ff3194c8f80895855396eb80a3d813 | from copy import deepcopy
from .BaseNews import BaseNews
from .MessageHandlers import Reader, Writer
from Model import Cell as ModelCell
class ViewOppBase(BaseNews):
huffman_prefix = "00010"
def __init__(self, cell: ModelCell):
super().__init__()
self.cell: ModelCell = deepcopy(cell)
def __str__(self):
re... |
15,401 | 5cb001730af3251a6fcbcf491490eb563b3db5cd | from collections import Counter
raw_data = open('06_input').read()
group_answers = list(map(lambda x: x.split('\n'), raw_data.split('\n\n')))
print("Part 1: ", sum(map(lambda gr: len(Counter(''.join(gr))), group_answers)))
unanimous_count = 0
for group in group_answers:
ans_dict = {}
for person in group:
... |
15,402 | 9d01f41266b14991d40f79896a59df8eb690b2f4 |
import os
import numpy as np
from matplotlib import pyplot as plt
import mwarp1d
#load data:
dir0 = os.path.dirname(__file__)
fnameCSV = os.path.join(dir0, 'data', 'Dorn2012.csv')
y = np.loadtxt(fnameCSV, delimiter=',')
y0,y1 = y[0], y[-1] #two trials for demonstration
#define landmarks and apply w... |
15,403 | 117035afc3f3bd5bc923bffbbe99b3484680cdc6 | from erode import erode
def dilate(imgname, outfile=None):
return erode(imgname, True, outfile)
|
15,404 | 3950d1dd7327ca89a0b53b84de885269631740de | """
Quiz for Data Structure
Q1: Which of the following sets of properties is true for a list?
Ans: Ordered
Mutable
Indexed
Q2: For a given data structure, ds, what is the correct way of calculating its length?
Ans: len(ds)
Q3: In a dictionary, key-value pairs are indexed by _____.
Ans: Keys
Q4: A... |
15,405 | 7221e063c276b4e3bde593227d48303999911fef | """added upvoted
Revision ID: 6dca8c020d2d
Revises:
Create Date: 2021-02-17 18:03:15.218694
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '6dca8c020d2d'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... |
15,406 | 30b4dfe1b9b7333939e04c37933bc2f04505fcaa |
#Get website url
#Crawler function
#inits the crawl
#makes a thread for each page being crawled
#tracks pages that have been crawled already
#Threading function
#create queues
#Crawled data function
#stores & handles all data from crawled pages
from bs4 import BeautifulSoup
import requests, argparse, pprint
all... |
15,407 | 4f9e1333bd38949ab147ca3cbe381a6c276524a8 | #
# @lc app=leetcode.cn id=788 lang=python3
#
# [788] 旋转数字
#
class Solution:
def rotatedDigits(self, N: int) -> int:
trans = {'0': '0', '1': '1', '2': '5',
'5': '2', '6': '9', '8': '8', '9': '6'}
count = 0
for i in range(N+1):
c = 0
for k in str(i):... |
15,408 | 11d3251966e31062663d51b4a378e7ed1fb58152 | f = open('./input.txt','r')
s = f.readlines()
f.close()
to_sum = []
for line in s:
mini = 0
maxi = 0
linearray = line.split()
print (linearray)
for num in linearray:
if (mini == 0) and (maxi == 0):
mini,maxi = int(num), int(num)
if int(num) < mini:
mini = int(num)
if int(num) > maxi:
... |
15,409 | 104e8b2e87e71dca58566d850357a13867d08f01 | import csv
data = []
with open('./forestfires.csv') as csv_data:
reader = csv.DictReader(csv_data)
for row in reader:
this_row = [float(row['temp']), float(row['wind']), float(row['rain']), float(row['RH'])]
data.append(this_row)
Examples = {
'ForestFires': {
'data': data,
... |
15,410 | 72fe9af1883ffce6f17eeaa507524220e3ebf865 | import pytest
from sklearn.datasets import load_iris
from sklearn.metrics import make_scorer
from sklearn.model_selection import cross_val_score
from sklearn.metrics import roc_auc_score
from sklearn.preprocessing.label import label_binarize
def roc_auc_avg_score(y_true, y_score):
y_bin = label_binarize(y_true, ... |
15,411 | bfe9db2a9588859aee9ea36e158a5a0c88f003f4 | #_*_encoding:utf-8
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Course(models.Model):
name = models.CharField(max_length=50,verbose_name=u'专题')
def __unicode__(self):
return self.name
class Meta:
verbose_name = u'专题'
verbo... |
15,412 | c1b12241d9af12e7a95a86a7d9774f7b9ea5a11f | # -*- coding: utf-8 -*-
# Copyright (C) Cardiff University (2018-2021)
# SPDX-License-Identifier: MIT
"""Tests for :mod:`gwosc.datasets`
"""
import re
from unittest import mock
import pytest
from .. import datasets
__author__ = 'Duncan Macleod <duncan.macleod@ligo.org>'
DATASET_JSON = {
'events': {
'... |
15,413 | 810e7fc3c7fead9bee6d9f20ffd3bde32a774940 | n = int(input())
scores = [int(x) for x in input().split()]
fix_scores = []
for i in range(n):
fix_score = scores[i] / max(scores) * 100
fix_scores.append(fix_score)
fix_average = sum(fix_scores) / n
print(float(fix_average)) |
15,414 | 23c95538ac9438eb6ff9e7381cccfeeac40c3d52 | import numpy as np
import cv2
# Loading image
image = cv2.imread("coins.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
cv2.imshow("Blurred Image", blurred)
# Applying adaptive thresholding
meanThresh = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv... |
15,415 | bf5a9016fbf437a22afd629f2c94b16470363521 | # python conv_reddit.py stopword_file reddit_pickle_files
# converting reddit pickle files to input files required for further processing
# files created :
# vocab1.txt : question vocab
# vocab2.txt : word vocab
# input_sc.txt : question word count data; (q_id word_id count)
# aux_data : question aux data; (link_Id na... |
15,416 | 8df47f93c2c2c6fcf6c2b44b5a93f88e33249806 | import sys
s_in = sys.stdin
while True:
content = s_in.readline().rstrip('\n')
if content == 'exitc':
break
print(content)
|
15,417 | a7779ec3f0964d0538a3d130d0df53dc6b33ffa2 | num = int(input("Enter a number: "))
if (num % 2) == 0:
print(num, "True")
else:
print(num, "False")
|
15,418 | 1bc959a7c01bac940c8725126fa77c80326f5a45 | # coding = utf-8
'''
@author = super_fazai
@File : use_bs4_css选择器.py
@connect : superonesfazai@gmail.com
'''
from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time the... |
15,419 | 2af98fb79655a9fce9dadecb1ba7962e53b280cd | N = int(input())
cnt = list(map(int, input().split()))
answer = [-1] * N
for i, num in enumerate(cnt):
curr_num = num
idx = 0
while curr_num or answer[idx] != -1:
if answer[idx] == -1:
curr_num -= 1
idx += 1
answer[idx] = i+1
print(" ".join(list(map(str, answer))))
|
15,420 | 4b3e5b3a15c638256323dfa7d2a1bab0bb6bed74 | #TASK - 2
#Program for 7 different methods of lists
#To initialize the list
random = [5, 7, 29, 37, 18]
#To print this list
print ("The list of these random numbers: ", random)
#The index of the elements
random.index(37)
print ("The index of the element 37 is: ", random.index(37))
#To Change the element at a parti... |
15,421 | 48ff85b2277fc8c85c2a523a086b44b8ec697602 |
#import the argv method from the sys module
from sys import argv
#declare the expected command line arguments
script,first_var,second_var,third_var = argv
print("The script using which the program was run" , script)
print("The first argument passed was",first_var)
#print the lenght of the number of arguments
print(f"... |
15,422 | 49ea7f3eee8aab1bd4c132e392cb7b0d20ed3cdd | #For a given array A of N integers and a sequence S of N integers from the set {−1, 1}, we define val(A, S) as follows:
#
#val(A, S) = |sum{ A[i]*S[i] for i = 0..N−1 }|
#
#(Assume that the sum of zero elements equals zero.)
#
#For a given array A, we are looking for such a sequence S that minimizes val(A,S).
#
#Write a... |
15,423 | 8326e7b51751ec0d5d2bd8d85f39bff87e644695 | # -*- coding: utf-8 -*-
from flask import Blueprint, jsonify, request, render_template
author_blueprint = Blueprint("author", __name__)
from models import Author
# @author_blueprint.route("/", methods=["GET"])
# def index():
# "首页入口"
# return render_template("author2.html")
@author_blueprint.route("/author"... |
15,424 | 25d04485b006db479a0e7355cc62f4070e02f09e | """
Check if the given string is a correct time representation of the 24-hour clock.
Example
For time = "13:58", the output should be
validTime(time) = true;
For time = "25:51", the output should be
validTime(time) = false;
For time = "02:76", the output should be
validTime(time) = false.
"""
def validTime(time):
... |
15,425 | a7668d53942ac2cf33cf026a90c97bdc0931ae09 | def sum(seq):
def add(x,y): return x+y
return reduce(add, seq, 0)
result=sum(range(1,6))
print result |
15,426 | a63134c940d6d660aaba64a689a6674aed56e73b | class Employee:
company="camel"
salary=100
location="kolkata"
@classmethod
def salaryChange(cls,sal):
cls.salary= sal
e = Employee()
print(e.salary)
e.salaryChange(400)
print(e.salary)
print(Employee.salary) |
15,427 | 49498b9428eb1d478f2ff8f991214122d2b6395b | #AI_bot
import config
import euclid
def norm(A):
if not A==0:
return A/abs(A)
else:
return 0
def AI_commands(state):
if (config.difficulty==0):
# ball1_1, ball1_2, ball2_1, ball2_2, puck, walls_left, walls_right, stopPower, wall_player1_goal, wall_player2_goal, goal_player1, goal_... |
15,428 | edeee2e685e3a43e3c3b82b842dced515269224b | #!/usr/bin/env python
import rospy
import time
from demo_test.srv import *
def test_server_fun():
# init service
rospy.wait_for_service('teleop_ctrl_service2')
rospy.wait_for_service('teleop_ctrl_service3')
rospy.wait_for_service('teleop_ctrl_service4')
teleop_srv_init2 = rospy.ServiceProxy('teleop... |
15,429 | 7fc259fdf9bcfe0d858c0f2baeb5e46a630a1dec | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv('../data/azureml/Bike_Rental_UCI_dataset.csv')
def day_of_week():
## First day in the dataset is Saturday
days = pd.DataFrame([[0, 1, 2, 3, 4, 5, 6],
["Sun", "Mon", "Tue", "Wed", "Thr", "Fri", ... |
15,430 | ea206c515bdd2c30badfc84c3f4b20630100052b | import glob
import numpy as np
import astropy.io.fits as pyfits
import commands
import sys
from drizzlepac import tweakreg, astrodrizzle
import collections
import copy
set_num = sys.argv[1]
def do_it(cmd):
print cmd
print commands.getoutput(cmd)
def get_filter(the_header):
try:
return the_header... |
15,431 | b728ad737fea657e56d0033daa1e4c82d37b2ecf | # -*- coding: utf-8 -*-
import os
import sys
sys.path.append('../Compiladores/')
#import uuid
#from typing import *
from afnd.automata import AFNDmV
'''
classe de conversao de afnd-e para afd pelo metodo de construção de subconjutos
recebe um afnd calcula os fechos e retorna um afd
'''
class AFD(AFNDmV):
#... |
15,432 | 69190e945486e38231286ff09f4c2d71f5d8973d | from django.core.exceptions import ValidationError
from rest_framework import status
from django.http import HttpResponseServerError
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import serializers
from rareserverapi.models import Category
from rareserverap... |
15,433 | 1d62ad79683208cec52f5b8aca9be4bfe26f4e89 | # Given an array, rotate the array to the right by k steps, where k is non-negat
# ive.
#
# Follow up:
#
#
# Try to come up as many solutions as you can, there are at least 3 different w
# ays to solve this problem.
# Could you do it in-place with O(1) extra space?
#
#
#
# Example 1:
#
#
# Input: n... |
15,434 | 8b1d394e3311620bd8e71f863c6255dd3d3e8d8c | #-*-coding:utf8-*-
#user:brian
#created_at:2018/6/9 10:18
# file: MultionormialNB.py
#location: china chengdu 610000
from Bayesmodel.Bacic import *
class MultinormialNB(NativaBsyes):
def feed_data(self,x,y,sample_weight=None):
if isinstance(x,list):
features=map(list,zip(*x))
else:
... |
15,435 | 268c394de7cad11353322e5d98230d1414c16e34 | '''
DESCRIPTION
This script reads HDF5 output files from The FLASH code and
extract its fields, data and computes the extent of the
mixing layer.
AUTHOR
Erik S. Proano
Embry-Riddle Aeronautical University
'''
import yt
from yt.funcs import mylog
import h5py
import numpy as np
import scipy.int... |
15,436 | 1e7f95853e36bbc1a47b8911c239736e7f68128b | if __name__ == "__main__":
from main_xml_creator import main
main()
|
15,437 | e7ed2dc0ce5d30b4bb8fdfa8ae2abdae16ca9eb3 | class Utwory_muzyczne():
def __init__(self,wykonawca,tytul,album,rok):
self.wykonawca = wykonawca
self.tytul = tytul
self.album = album
self.rok = rok
def __str__(self):
return f'Wykonawca: {self.wykonawca}\nUtwór: {self.tytul}\nAlbum: {self.album}\... |
15,438 | c3380c9fa633c0253a66ffb739b5013fb9e86d17 | import logging
import time
from functools import wraps
from threading import Lock
from googleplay_api.googleplay import GooglePlayAPI, LoginError, DecodeError
logging.basicConfig(format='%(asctime)s [%(levelname)s] %(module)s.%(funcName)s - %(message)s')
logger = logging.getLogger('googleplay-proxy')
logger.setLevel(... |
15,439 | 4fad3aa05fc6c9842fc98a0082a9e1672ccf6ffc |
"""
function provided by Riccardo Manzoni for scaling
double tau trigger MC to data
22 Feb 2016
Updated 30 Jan 2017 to include data/MC scale factors
"""
import math
import ROOT
import json
from helpers import getTH1FfromTGraphAsymmErrors
class DoubleTau35Efficiencies :
"""A class to provide trigger efficiencie... |
15,440 | 1751798fa6bc81445979bcbf8dd35a7364c54049 | import re
# Patterns for all regular expressions
GENERAL_PATTERN = r'^([A-Z0-9]{3}|[A-Z0-9]{4})\ [A-Z0-9]{3}$'
AA9A_PATTERN = r'^(^(WC[12]|EC[1-4]|SW1)[ABEHMNPRVWXY]$|SE1P|NW1W)$'
A9A_PATTERN = r'^(E1W|N1[CP]|W1[ABCDEFGHJKPSTUW])$'
A9_PATTERN = r'^([BEGLMNSW][1-9])$'
A99_PATTERN = r'^([BEGLMNSW][1-9]\d)$'
AA9_PATTERN ... |
15,441 | 18702b23c16c1fbb8cbaf7154c04d1b5384c1aea | ## Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.
## create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890"
def create_phone_number(n):
#your code here
if len(n) > 10:
return print... |
15,442 | 273219d52422dcbcb3ad064b101cfcba185c5a17 | #!/usr/bin/env python
#
# Copyright 2007 Google 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 o... |
15,443 | 7f5d6eb9f09b352052404cba431eb82324268153 | class Solution:
# @return a list of lists of integers
def generate(self, numRows):
s = []
for i in xrange(0, numRows):
s.append([1])
if i == 0:
continue
elif i == 1:
s[i].append(1)
continue
... |
15,444 | dde69318f001346ed53108cd97310ac137d40590 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/11/9 11:53
# @Author : maxu
# dict
# Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度
d ={'A':90,'B':55,'C':27}
print(d['B'])
# 把数据放入dict的方法,除了初始化时指定外,还可以通过key放入
d['D']=666
print(d['D'])
# 由于一个key只能对应一个value,所以,多次对... |
15,445 | 5c4a20dcf966d3e8dbeb4c153a2de66e78d9b580 | """ https://leetcode.com/problems/reducing-dishes/
1. sort the dishes
2. define the knapsack problem
choose dish: (i+1-dis)*A[i]+dp(i+1, dis)
discard dish: dp(i+1, dis+1)
"""
from header import *
class Solution:
def maxSatisfaction(self, A: List[int]) -> int:
A.sort()
@cache
... |
15,446 | c09626405cd0c661e1d840078a00fa6588d91ea3 | from typing import Dict, Any, List, Optional
import yaml
import json
from json import JSONEncoder
import os
import re
import datetime as dt
import pandas as pd
from pprint import pprint
from pathlib import Path
from bs4 import BeautifulSoup
from bs4.element import Tag
import numpy as np
HOME = Path( os.getenv('HOME')... |
15,447 | 8b614955cfbf5bebfbf86b438adfbad5665c6681 | import os
import paho.mqtt.client as mqtt
from flask import Flask, render_template, send_from_directory
client = mqtt.Client()
client.connect("moorhouseassociates.com", 1883, 60)
app = Flask(__name__)
@app.route('/css/<path:path>')
def send_css(path):
return send_from_directory('css', path)
@app.route('/')
d... |
15,448 | 6bd102d64c86860d0718e0f634a7da07b09a8d32 | import re
class Container(object):
"""
Abstract container class which makes everything that inherits from it behave like a list.
"""
def __init__(self, items=None):
"""
Create new container, optionally preset with given items.
:param items: Items to preset the container... |
15,449 | 54109345febac6475126f30deda05578acb174d9 | from torchvision import transforms
from torchvision.datasets import MNIST
import torch
from PIL import Image
import numpy as np
from tqdm import tqdm
class MNISTInvase(MNIST):
def __init__(self, *args, **kwargs):
super(MNISTInvase, self).__init__(*args, **kwargs)
def __getitem__(self, index):
... |
15,450 | 2a3e02a24dc30cf064ce08ee2dcde1db746443b7 | from flask import Flask
app = Flask(__name__)
import flaskr.main
from flaskr import db
db.create_books_table() |
15,451 | 985b3c2c2443b32b3db3ce86bb89ef11e913a555 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'add_vin_regiune.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_Dialog(object):
def setupUi(self, Dialog):
... |
15,452 | 5685ad5c83e1c2a7f8c52bfd237d24268aab57dd | #!/usr/bin/env python
from boxoffice.models import *
from datetime import date
from dateutil.relativedelta import relativedelta
def init_data():
db.drop_all()
db.create_all()
user = User(userid="U3_JesHfQ2OUmdihAXaAGQ", email="test@hasgeek.com")
db.session.add(user)
db.session.commit()
one_... |
15,453 | f784bf7fd25f7d7de5b4449cf06cca4676e7726a | count = 0
total = 0
largest_so_far = float('-Inf')
smallest_so_far = float('Inf')
print('Before', total, count, largest_so_far, smallest_so_far)
while True:
line = input('> ')
if line == 'done':
break
try:
line = float(line)
count = count + 1
total = total... |
15,454 | 04c74385c5d78841de914b54031d1d243721d5b5 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'kgy'
import tesserocr
from PIL import Image
def hello_world():
image = Image.open('CheckCode.jpg')
result = tesserocr.image_to_text(image)
print(result)
image = image.convert('L')
image.show()
image = image.convert('1')
image.sho... |
15,455 | 04e2a9f7f9f308702b19d3f623d8aff47ea80831 | import time
import sys
import random;
path_to_config = "/home/provconf/adil/conf.txt"
path_to_non = "/home/provconf/adil/van.txt"
N = 1000000
config_perc = int(sys.argv[1]);
config_percent = config_perc/100.0
L = list(range(1, N+1))
random.shuffle(L) # shuffles in-place
# print(L)
config_numbers = config_percent ... |
15,456 | 9053b41a8d7ad8a9349533a3e303112ae276ea59 | """ Data Discovery '/data' """
from flask.views import MethodView
from .. import gateway as gw
class ProductApi(MethodView):
decorators = [
gw.get_decorator("validate"),
gw.get_decorator("auth")
]
def get(self, user_id:str=None, data_id:str=None):
arguments = {"qtype": "products"... |
15,457 | 0187bdeceb131e7e30b2a625e165932d10af83b7 | #!/usr/bin/env python3
#
# Copyright (c) 2021 LunarG, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modif... |
15,458 | d1f979a192eba53872c63ed56e9d39f5e5da7fa7 | from __future__ import unicode_literals
import six
import copy
from itertools import chain
from rest_framework.renderers import BrowsableAPIRenderer
from rest_framework.response import Response
from rest_framework.serializers import ListSerializer
from drf_sideloading.renderers import BrowsableAPIRendererWithoutFor... |
15,459 | f4788375b7d0920a3ff4208aa6203fd79823336e | # sub-parts of the U-Net model
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils import params
class double_conv(nn.Module):
'''(conv => BN => ReLU) * 2'''
def __init__(self, in_ch, out_ch, unet_norm, activation, padding, padding_mode, up_mode, doubleConvTranspose):
supe... |
15,460 | acffdf17d1086689281d9d346fe24a1627151e9d | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
data_path = '../tfrecord/many2one.tfrecords' # address to save the hdf5 file
with tf.Session() as sess:
feature = {'image': tf.FixedLenFeature([], tf.string), 'label': tf.FixedLenFeature([], tf.int64)}
# create a list of filenames and pas... |
15,461 | 284a092bd9ed1c037e354fc12e91df03bcab8b8a | #!/usr/bin/env python
# coding=utf-8
import rospy
from std_msgs.msg import Float32
from std_msgs.msg import Int64
import numpy as np
import requests
import threading
# 数据格式定义:time,car_speed,reel_speed,cb_speed,reel_current,cm7290_current,cb_current
class Interpreter:
def __init__(self):
self.init_time =... |
15,462 | 37e3d3edf99f7be7d794c12fd485f37b92ea59fc | # -*- coding: utf-8 -*-
import os.path
from fabric.api import env, task, run, put, cd, sudo
from fabric.contrib.files import exists, append, contains, sed
from .utils import mkdir
from . import conf_file
env.use_ssh_config = True
BASE_PATH = '$HOME/tmp-fabric-toolkit'
@task
def test():
"""执行uname -a命令"""
... |
15,463 | c9864bc74f80fe08cc36bba9b7cb2ff2779cd955 | import os
import pytest
import glob
from VCF.VCFfilter.BCFTools import BCFTools
# test_vcfFilter_BCFTools.py
@pytest.fixture
def vcf_object():
'''Returns an object'''
vcf_file = pytest.config.getoption("--vcf")
bcftools_folder = pytest.config.getoption("--bcftools_folder")
vcf_object=BCFTools(vcf=vc... |
15,464 | d21e6f5bdab2767c81ac29223d343fa7fcbcc4a0 | from .utils import expire_page
class ExpireCacheMiddleware(object):
def process_request(self, request):
if '__placeholder_expire_page' in request.GET:
expire_page(request.path)
def process_response(self, request, response):
if '__placeholder_expire_page' in request.GET:
... |
15,465 | 0c3e226138d44858122d9846ed7085e7b2fe6c49 | """Scrape property sales information from QV.co.nz."""
import requests
from datetime import datetime
from settings import settings
SALES_SHEET = "Sales"
COLUMNS = ["Property", "Sale price", "Sale date", "Rates value"]
ID = "Property"
REQUEST_DATA = {
"MIME Type": "application/x-www-form-urlencoded; charset=UTF-8"... |
15,466 | 69ad01852b9bb55254cd551ba85b973991d9ba43 | class Person(object):
def talk(self):
print('talk')
def run(self):
print('run person')
class Car(object):
def run(self):
print('run')
# left high priority
class PersonCarRobot(Car, Person):
def fly(self):
print('fly')
person_car_robot = PersonCarRobot()
person_car_ro... |
15,467 | ba187610427618a4e3026f14191523c00ae5a111 | import pygame
from random import randint
main_display = pygame.display.set_mode((800, 600))
bg = pygame.image.load('forest.jpg')
mosquito_raw = pygame.image.load('mosquito.png')
bg = pygame.transform.scale(bg, (800, 600))
mosquito = pygame.transform.scale(mosquito_raw, (150, 150))
mosquito_rect = mosquito.ge... |
15,468 | 9dc646253470bca38c641a15482a16cd4349135b | # -*- coding: utf-8 -*-
from flask import Flask, Response, make_response, render_template, request
import numpy as np
import pandas as pd
from bokeh.plotting import figure, output_file
from bokeh.embed import components
from bokeh.charts import Histogram
app = Flask(__name__)
# Import dataset
data = pd.read_csv('da... |
15,469 | c4042d835cf2257ca1835c7471940370a7c8e2f9 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data=pd.read_csv("linear.csv")
x=data["metrekare"]
y=data["fiyat"]
x=np.array(x)
y=np.array(y)
#plt.scatter(x,y)
#plt.show()
m,b=np.polyfit(x,y,1)
print("en uygun eğim" ,m)
print("en uygın b değeri",b)
uzunluk=np.arange(200)
plt.scatter(x,y)
... |
15,470 | 664c698a04b6046666f0171b26b5aadff343d550 | from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Ingredient(models.Model):
name = models.TextField(verbose_name='ingredient_name')
units = models.TextField(verbose_name='units')
def __str__(self):
return self.name
class Meta:
... |
15,471 | 5a6c14c4cefbcb00ad403c8d4cb445680f784c1a | from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse('Hello world!')
def hello(request):
return render(request, 'hello.html', {
'test': 'aa',
}) |
15,472 | 92d6756b1946940fd08ab49577f4701d965f9e94 | """
starter.py
All text enclosed in triple quotes (regardless of line breaks inside) will turn into a comment.
Comments will be ignored when the code, which means we can use this to document what our code does.
"""
# using a hashtag is another way to comment. you need another hashtag if you are going to use multipl... |
15,473 | 8a7899012bd32a7fd13f78da0232c3309e127687 | import csv
import utility
def convert_to_float(string_vector):
vector = []
for item in string_vector:
vector.append(float(item))
return vector
def get_features_list(csv_file):
data_set = []
with open(csv_file) as f:
data_set_count = sum(1 for line in f) - 1
with open(csv_fil... |
15,474 | 5c52a1c8752c66c349175566d0051d1508c6ad46 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 22 2021
@author: George Yiasemis
"""
import numpy as np
# The Agent class allows the agent to interact with the environment.
class Agent():
# The class initialisation function.
def __init__(self, environment, gamma=0.9, reward_fun=None):
... |
15,475 | edcdd247adc037930ba1d18ec9ab9b89711bc1ca | #!/usr/bin/env python
from __future__ import print_function
from base64 import b64decode, b64encode
from hashlib import md5, sha1, sha256
from os.path import join
from subprocess import Popen, check_output
import binascii, hmac, os, platform, tarfile
import Queue, random, re, shutil, signal, sys, time
import SimpleHT... |
15,476 | a362c0ad1ca72b9625a07b6368fd389de807bbb8 | class PluginExercise:
def __init__(self, name, description, content, test_case_list, solution,language):
self.name = name
self.description = description
self.content = content
self.test_case_list = test_case_list
self.solution = solution
self.language = language |
15,477 | 9c6ae44ada190712300a458d5852a64f75a3b4b8 | import pretty_midi
import smidi
import pickle
import os
import re
import numpy as np
from hyperps import n_features_in, n_features_out
DATA_DIR = 'data'
PICKLE_DIR = os.path.join(DATA_DIR, 'pickles')
DUMP_SIZE = 600
def generate(dirs=None, pickle_name='data', accepted_keys=None):
'''
Loads smidis of dirs
... |
15,478 | 47d214429dd174598b7b838902415b40d4bd4966 | def druglike_molecules(self, idx):
"""
Restrictions are in order of [hbond_donors, hbonds_acceptors, has_disorder, has_3d_structure, is_organometallic, is_polymeric, is_organic, r_factor, molecular_weight]
"""
restrictions = {"hbond_donors":[None, 5], "hbond_acceptors":[None, 10], "h... |
15,479 | 6d4b0d555831443382d322c28a40aae0c7bb2f82 | #-*- coding:utf-8 -*-
class Pen:
def write(self):
print "펜으로 필기를 해요"
print "myutil/Util.py 모둘에 실행순서가 들어왔습니다."
print 'Util __name__:',__name__
if __name__=='__main__':
print "Util.py 모듈이 main으로 실행 되었습니다." |
15,480 | 1f2efd980402681e3d433cd3ba6f09297df2da28 | """
Rotting Oranges
Q. In a given grid, each cell can have one of three values:
the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rott... |
15,481 | 1cb3eaf190e51ba6b7e5280566434f09c85bd101 | import math
def snt(n):
if n<2: return False
for i in range(2, int(math.sqrt(n))+1):
if n%i==0:
return False
return True
t=int(input())
for i in range(t):
s=input()
check=True
for i in range(0, len(s)):
if snt(i)==True and snt(int(s[i]))!=True:
check=... |
15,482 | 3b918b3af84ad9383b600c8d9e709757e243e0df | from django import template
import string
from ..api import request_song
register = template.Library()
@register.simple_tag
def get_slug(value):
temp = ''
for i in value:
if i == '0' or i== '1' or i == '2' or i== '3' or i == '4' or i == '5' or i == '6' or i == '7' or i == '8' or i == '9':
t... |
15,483 | 0e69df9a1426639abb416463f7532979ae3c9468 | def main():
x, y, z = map(int, input().split())
ans = 0
while x > 0 and y > 0:
x -= 1
y -= 1
ans += 1
w = max(x, y)
while w > 0 and z > 0:
w -= 1
z -= 1
ans += 1
while z > 1:
z -= 2
ans += 1
print(ans)
if __name__ == "__m... |
15,484 | 9d2a61454a420960efce2556ca75635aa8c83560 | """Automated breaking of the Atbash Cipher."""
from lantern.modules import simplesubstitution
from typing import Iterable
# TODO: Consider using an affine cipher for transformation in future
KEY = 'ZYXWVUTSRQPONMLKJIHGFEDCBA'
def decrypt(ciphertext: str) -> Iterable:
"""Decrypt Atbash enciphered ``ciphertext`... |
15,485 | e6ca3b9881f0f2b8b14e8246e6587bbdbafdd639 | # Input
import speech_recognition
from gtts import gTTS
import os
robot_ear = speech_recognition.Recognizer()
with speech_recognition.Microphone() as mic:
print("[AI]: listening...")
audio = robot_ear.listen(mic)
robot_brain = "I don't know wtf you r talking 'bout! Have a nice day :)"
try:
your_order = r... |
15,486 | fac0d29023aff111a19c99521921b9e8e4ee04bd | #######################################################
# Everything to do with reading the grid
# This relies on a NetCDF grid file. To create it, run MITgcm just long enough to produce one grid.t*.nc file for each tile, and then glue them together using gluemnc (utils/scripts/gluemnc in the MITgcm distribution).
####... |
15,487 | f7344cb4a1e9c8796f5203958bec7780aa5e52db | #server.py
from wsgiref.simple_server import make_server
from hello import application
# 创建一个server
httpd = make_server('', 8000, application)
print('Server Http on port 8000')
# 开始监听http请求
httpd.serve_forever()
|
15,488 | d6f87dcd4d5b0aaa302907372d3e9f51e434f801 | from selenium.webdriver.common.by import By
class MainPageLocators():
MAIN_LINK = (By.CSS_SELECTOR, '#login_link')
BROWSE_STORE = (By.ID, "browse")
ALL_BOOKS = (By.XPATH, "//*[@id='browse']/li/ul/li[1]/a")
HEADER_ALLBOOKS = (By.CLASS_NAME, "action")
class LoginPageLocators():
LOGIN_FORM = (By.ID... |
15,489 | e0374da62c3669725daf1b69fa67ec88868d1b4f | import tensorflow as tf
from PIL import Image
from time import time
import numpy as np
from ops import *
import parameters
import os
dict = parameters.import_parameters( 'PARAMETERS.txt' )
NUM_BLOCKS = int( dict['num_blocks'] )
ALPHA = int( dict['alpha'] )
FIRST_CHANNELS = int( dict['first_channels'] )
SCALE = int( d... |
15,490 | 92e8ab65bfe4d76476ef4bb1978d42d4a772dac2 | import sys
import socket
import argparse
# Resolve the DNS/IP address of a given domain
# data returned in the format: (name, aliaslist, addresslist)
# Returns the first IP that responds
def getIP(d):
try:
data = socket.gethostbyname(d)
ip = repr(data)
return ip
except Exc... |
15,491 | 15cee00fdc26cde07785fa228cea8c11f816e9e2 | import abc
class XmlFile:
@abc.abstractmethod
def get_xml_file_name(self):
pass
def as_string(self):
xml_string = "<log>"
with open(self.get_xml_file_name()) as f:
for line in f:
xml_string += line
xml_string += "</log>"
return... |
15,492 | dd510f2899334787445b3c6f3de9b28894289e25 | Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> j = 9
>>> for i in range(1,10,2):
print(" "*j+i*"*")
j=j-1
|
15,493 | fbfaf4d8cfc9b2567ef663d119268f32d8e4bb55 | #!/usr/bin/env python
"Plot the concentration field rho(x,y) in the course of time"
from __future__ import print_function, division
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('file', type=str, help='H5MD datafile')
parser.add_argument('--species', type=int, default=1)
pa... |
15,494 | 498067c160f0f77bdaed10afce9718f7bfc17614 | import random
import string
f = open("twist.txt","r") #opens file with name of "test.txt"
me=f.readline()
print ("Loading word list from file...")
me = str.split(me)
men=len(me)
me=random.choice(me)
##print(f.read(55))
print (me)
print (men)
f.close()
##print ("Loading word list from file...")
### inFile: file
##inFi... |
15,495 | d2604a6ee92ab6155f0e567261df729f51451f45 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""CNN_using_persistence_images_on_patch.py
The aim of this script is to perform the training of a CNN using persistence
images as a input. This script is inspired from this script:
BorgwardtLab/ADNI_MRI_Analysis/blob/mixed_CNN/mixed_CNN/run_Sarah.py
To get real time info... |
15,496 | dfecc9483db97c935ce32eae7529acd7e3849dea | from statistics import YouTubeStats
API_KEY = 'set your youtube data api here'
channel_id ='channel id'
channel_title = 'channel title'
if __name__ == "__main__":
channel_stats = YouTubeStats(API_KEY, channel_id, channel_title)
channel_stats.get_channel_stats()
channel_stats.stats_to_json_file()
|
15,497 | 655dd2b7327e51f2d4008fcdb5f48478a9e5fe22 | from tests.unit.dataactcore.factories.domain import TASFactory
from tests.unit.dataactcore.factories.staging import AppropriationFactory, ObjectClassProgramActivityFactory
from tests.unit.dataactvalidator.utils import number_of_errors, query_columns
_FILE = 'a35_cross_file'
_TAS = 'a35_cross_file_tas'
def test_colu... |
15,498 | faf4a65493554480327c606e40ad540f2699eb82 | weekdays = ['mon','tues','wed','thurs','fri']
print(weekdays)
print(type(weekdays))
days = weekdays[0] # elemento 0
print(days)
days = weekdays[0:3] # elementos 0, 1, 2
print(days)
days = weekdays[:3] # elementos 0, 1, 2
print(days)
days = weekdays[-1] # ultimo elemento
print(days)
test = ... |
15,499 | 43a731a276e54b449fe01315d818af4d650fdb7b | import pprint
import sys
# The ANSI colours below break Conjure's ability to parse REPL input/output
# sys.ps1 = "\033[0;34m>>> \033[0m"
# sys.ps2 = "\033[1;34m... \033[0m"
sys.displayhook = pprint.pprint
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.