index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
2,600 | 033719313f92aaf3c62eb1b07a9aa08f13c7bb6e | #!/usr/bin/python
#
# Author: Johnson Kachikaran (johnsoncharles26@gmail.com)
# Date: 7th August 2016
# Google Drive API:
# https://developers.google.com/drive/v3/reference/
# https://developers.google.com/resources/api-libraries/documentation/drive/v3/python/latest/
"""
Includes functions to integrate with a u... |
2,601 | 94f50e371ef65e86d0d2d40a3ed16946f8811be3 | from django.apps import AppConfig
class TimestechConfig(AppConfig):
name = 'TimesTech'
|
2,602 | b8957acb71d435a93b4397a24d3b5cf4b2a817f8 | # -*- coding: utf-8 -*-
'''
Created on 2014/07/24
@author: seigo
'''
from google.appengine.api import users
from google.appengine.ext import webapp
from MyModel import HistoricalTable, PollRating, Government
from datetime import datetime
hts = [["2014/7/1","集団的自衛権行使容認の閣議決定","http://www.47news.jp/47topics/e/254919.ph... |
2,603 | 34d011727c93bb4c8ccf64017e7185717ef98667 | x=25
y=43
print(x&y)
print(x>>y)
print(x^y)
print(x|y) |
2,604 | e9c439eafac8fd689980ffcb562f3b5ee903dd56 | from pylab import *
def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
X,Y = np.meshgrid(x,y)
axes([0.025,0.025,0.95,0.95])
contourf(X, Y, f(X,Y), 8, alpha=.75, cmap=cm.hot)
C = contour(X, Y, f(X,Y), 8, colors='black', linewidth=.5)
clabel(C, inline=1, fo... |
2,605 | 3d43bf0d0ca1df06b3647a33f88cee067eeff9f4 | from django.test import TestCase, Client
from accounts.models import Account
from .data import account
from rest_framework import status
class TestAccountRequests(TestCase):
def setUp(self):
self.client = Client()
self.superuser = Account.objects.create_superuser(**account)
def test_register... |
2,606 | 498d07421d848332ad528ef3d3910d70312b5f55 | from Domain.Librarie import vanzare_obiect, get_id, get_titlu, get_gen, get_pret, get_tip_reducere
def inverse_create(lst_vanzari, id_carte):
new_vanzari = []
for carte in lst_vanzari:
if get_id(carte) != id_carte:
new_vanzari.append(carte)
return new_vanzari
def get_by_id(id, lista):... |
2,607 | e7e9a53d4c41448521b324d51641a46827faa692 | from http import HTTPStatus
#from pytest_chalice.handlers import RequestHandler
import app
from chalice.test import Client
def test_index_with_url():
with Client(app.app) as client:
response = client.http.get('/?url=https://google.com')
assert response.status_code == HTTPStatus.MOVED_PERMANENTLY
... |
2,608 | 4f3e297b6925f8d65aacaa59bb837e746747c33f | import torch
from torch import nn
import torch.nn.functional as F
class JointModel(nn.Module):
def __init__(self, d_v, d_e, d_t, encoder_layers, generator_layers,encoder_shortcut, generator_shortcut, generator_transform,
num_word, emb_size, word_rnn_size, word_rnn_num_layer, word_rnn_dropout, word... |
2,609 | 6aeaa2ed01e0c0dac54cd8220c5da005fccc53e9 | '''
Created on 18/10/2012
@author: matthias
'''
import os
import errno
import uuid
import glob
import shutil
import sys
import subprocess
import time
import pickle
import common.pbs
def prepare_directories(options, extension, subversiondir=None):
# extract datadir from options
datadir = options['datadir']
... |
2,610 | fbde00d727d7ea99d1a7704f46cb9850c8b210d7 | import pygame
import wave
import threading
import numpy as np
import pylab
import struct
import io
from PIL import Image
import sounddevice as sd
# 处理音频频谱
# voice.wav 格式:8000 rate 16bit 单声道
class SpectrumMap:
def __init__(self):
FILENAME = 'Sound/SoundResource/voice.wav'
self.wavefile = wave.open(... |
2,611 | 03156992355a756b2ae38735a98251eb611d4245 | import helper
__author__ = 'AdrianLeo'
helper.greeting("Hey, dummy")
|
2,612 | f7886f8d98ad0519f4635064f768f25dad101a3d | import numpy as np
import cv2 as cv
import random
import time
random.seed(0)
def displayImage(winName, img):
""" Helper function to display image
arguments:
winName -- Name of display window
img -- Source Image
"""
cv.imshow(winName, img)
cv.waitKey(0)
################################... |
2,613 | 2941ecde72325d46b5c3899d4b1a213daff67147 | from azureml.core.compute import AksCompute
from azureml.core.model import Model, InferenceConfig
from azureml.core.webservice import AksWebservice
workspace_name = ""
subscription_id = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
resource_group = "XXXXXXXXXXXXXXXXX"
workspace_region = "eastus2"
https_cert = "XXXXX"
aks_nam... |
2,614 | de286b94e09db477e3d920a9eff1a299474baf20 | #!/usr/bin/env python
import mcvine.cli
from numpy import array
from mcvine_workflow.singlextal.resolution import use_res_comps as urc
beam_neutrons_path = '/SNS/users/p63/ORNL_public_research/MCViNE_Covmat_comparison/mcvine_resolution/beams/beam_30_1e9/out/neutrons'
instrument = urc.instrument('ARCS', '3.*meter', '13.... |
2,615 | 80969de6924ae5fe6bb8e7f1211e7aca28c63989 | # a little more thing to be done.
def eval_loop():
while True:
s = input('Please input: ')
if s != 'done':
print(eval(s))
else:
break
eval_loop() |
2,616 | ee58ed68d2f3c43f9611f6c6e4cd2b99adcb43d2 | import bz2
import json
import os
from pyspark.context import SparkContext
from pyspark.accumulators import AccumulatorParam
import numpy as np
from scipy import spatial
import pandas as pd
import re
import operator
import csv
CACHE_DIR = "D:\TwitterDatastream\PYTHONCACHE_SMALL"
EDU_DATA = 'merged.csv'
TRAIN_FEAT_CSV =... |
2,617 | f3644b42d1a6c87c6169f8d123dadf6cd209270c | name = ''
while name != 'your name' and name != 'Your name':
print('Please type your name.')
name = input()
print('Thanks!')
#while 1 == 2 or :
# print('Type your name')
# name = input()
# if name == 'your name':
# break
#print('Thanks!')
|
2,618 | 497f56891670f635feff983058e86055e54be493 | """
- Define a new class Student which is derived from Human and has:
grade field.
do_hobby - print 'dancing' or some another hobby
"""
import andy.Lesson_7.exercise_1
class Student(andy.Lesson_7.exercise_1.Human):
def __init__(self, firstname, lastname, grade):
super().__init__(firstname, lastname)
... |
2,619 | 231a07e63e40f2e4d204cde76c52e64b922da1b8 | import socket
import time
class FileTransProgram(object):
def __init__(self, ADDR, file_name):
self.ADDR = ADDR
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect(ADDR)
self.file_name = file_name
def recv(self):
self.sock.send(bytes("Connec... |
2,620 | df5c79c79d827b6b3de7ceb4b1e3c652c8956346 | input = """
t(Z) :- t0(Z).
t(Z) :- g(X,Y,Z), t(X), not t(Y).
t0(2).
g(5,1,3).
g(1,2,4).
g(3,4,5).
"""
output = """
t(Z) :- t0(Z).
t(Z) :- g(X,Y,Z), t(X), not t(Y).
t0(2).
g(5,1,3).
g(1,2,4).
g(3,4,5).
"""
|
2,621 | bee7f3acdb103f3c20b6149407854c83ad367a6b | #!/usr/bin/python3
"""
This module add a better setattr function
"""
def add_attribute(obj, name, value):
""" add an attribute to a class if possible"""
if hasattr(obj, "__dict__"):
setattr(obj, name, value)
else:
raise TypeError("can't add new attribute")
|
2,622 | 92b71c67130cd37b2143fbd9ad71fe9a18b3f7e8 | import requests
from bs4 import BeautifulSoup
import time
print("Put some unfamiliar skills")
unfamilar_skills = input(">")
print(f"Filtering result for {unfamilar_skills}...\n")
def find_jobs():
html_text = requests.get('https://www.timesjobs.com/candidate/job-search.html?searchType=personalizedSearch&from=submit... |
2,623 | d04e69c234f2887f5301e4348b4c4ec2ad3af7a2 | '''
Write the necessary code calculate the volume and surface area
of a cylinder with a radius of 3.14 and a height of 5. Print out the result.
'''
pi = 3.14159
r = 3.14
h = 5
volume = pi*r**2*h
surface_area = 2*pi*r**2+r*h
print(volume,surface_area) |
2,624 | d61151859390ab1c907ac3753143312da434981e | '''4. Write a Python program to filter the positive numbers from a list.'''
lst = [1, -3, 4, -56, 7, 3, -8, -5, 2, 4, 9]
New_list = list(filter(lambda x: x > 0, lst))
print(New_list)
|
2,625 | fbb1254c7166fa2aa9cd8a0b9c6525dbe5b652a0 | #!/usr/bin/env python3
import re
import datetime
import math
import pathlib
import os
import io
import argparse
import subprocess
import xml.sax.saxutils
from typing import (Optional, List, Iterable)
import sys
_DEFAULT_TRACK_TYPE = 'Dashcam track'
class Arguments(object):
def __init__(self):
parser = ... |
2,626 | c331802cf5a09bc8db8ddbfa37636a01cf73684e | # coding: utf-8
import sys
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from flask_assets import ManageAssets
from app import app
from assets import assets
from db import db
from .changepassword import ChangePassword
from .create_superuser import SuperUserCommand
from .... |
2,627 | 45449e728dadd241b00f5c4bfb3fd3950f04037c | class Background(object):
def __init__(self, name):
self.name = name
self.description = ''
self.prTraits = []
self.ideals = []
self.bonds = []
self.flaws = []
def getBackName(self):
return self.name
def setBackDesc(self,desc):
self.descriptio... |
2,628 | dff5e75460637cf175b1b65af3320d01dc2e35b6 | from django.db import models
from django.utils import timezone
class User(models.Model):
class Meta:
db_table = "User"
app_label = "backlog"
webin_id = models.CharField(
"ENA's submission account id", max_length=15, unique=True, primary_key=True
)
registered = models.BooleanFi... |
2,629 | 709e54daea4fea112539af3da83b00a43a086399 | import pandas as pd
df = pd.read_csv("search.csv")
df0 = df[df['re_0']<df['re_1']]
df1 = df[df['re_0']>df['re_1']].ix[:, ['re_1', 'im_1', 're_0', 'im_0']]
df1.columns = ['re_0', 'im_0', 're_1', 'im_1']
df = pd.concat([df0, df1]).sort_values(by=["re_0"])
eps = pow(10.0, -4.0)
first = True
res = []
val_old = None
fo... |
2,630 | 55a26eb2625acb201677f5ff50fde809402c9b93 | import json
import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dangjianyun.settings")# project_name 项目名称
django.setup()
from dangjiansite.djfuncs import *
import os
import datetime
import requests
import time
import urllib3
import base64
import csv
import random
from bs4 import Beautifu... |
2,631 | fe7fb9a4a5ca2bb8dab0acf440eb2fac127264ce | #!/usr/bin/env python
from google.appengine.ext.webapp import template
from google.appengine.ext import ndb
import logging
import os.path
import webapp2
import json
from webapp2_extras import auth
from webapp2_extras import sessions
from webapp2_extras.auth import InvalidAuthIdError
from webapp2_extras.auth import ... |
2,632 | 8dcd4914c58a7ecafdfdd70b698ef3b7141386a6 | alunos = list()
while True:
nome = str(input('Nome: '))
nota1 = float(input('Nota 1: '))
nota2 = float(input('Nota 2: '))
media = (nota1+nota2)/2
alunos.append([nome, [nota1, nota2], media])
pergunta = str(input('Quer continuar [S/N]? ')).upper()[0]
if pergunta == 'N':
break
print('-... |
2,633 | 46fd4b976526a1bc70cf902bdb191feea8b84ad9 | import pygame
import time as time_
import random
import os
from pygame.locals import *
from math import sin, cos, pi
from sys import exit
# ---------------------------
from unzip import *
unzip()
# ---------------------------
from others import *
from gaster_blaster import *
from board import *
from bone import *
from ... |
2,634 | 164b0afde225119a8fbd4ccfccbbbc3550aa75fe | import json
import os
import numpy as np
import pandas as pd
import py4design.py2radiance as py2radiance
import py4design.py3dmodel.calculate as calculate
from py4design import py3dmodel
__author__ = "Jimeno A. Fonseca"
__copyright__ = "Copyright 2017, Architecture and Building Systems - ETH Zurich"
__credits__ = ["J... |
2,635 | 365d031a31f3596df6fb71e620c293382d6ead1f | import os
import numpy as np
import networkx as nx
from matplotlib import colors, cm
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
from mpl_toolkits.mplot3d import Axes3D, art3d
from typing import Union, Sequence, List, Tuple, Optional
import wknml
from wkskel.types import Nod... |
2,636 | 2b1ec29d665aa93cd53644b62efcd1305b34e13e | print('Welcome aboard, Oleksij!')
|
2,637 | 4550ed971eef36badf46a44adcc593324a5292cf | from typing import Optional,List
from fastapi import FastAPI
from pydantic import BaseModel, Field
from redisqueue import RedisQueue,MyRedis
import random
class Award(BaseModel):
name: str
count: int
class Item(BaseModel):
luckname: str = Field(...,title="抽奖规则名称",max_lenght = 300)
total: int = Field... |
2,638 | 09284a96467b09c2ad7b65530c015fdb64b198a4 | # Copyright 2016 Osvaldo Santana Neto
#
# 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 ... |
2,639 | a945d7f673d009a59e597cd3c99a886094ea9e57 | import sys
import json
import eventlet
import datetime
import flask
from flask import Flask
from flask import render_template
__version__ = 0.1
PORT = 8000
HOST = '0.0.0.0'
DEBUG = False
RELDR = False
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secretkey'
@app.route('/login/')
def login():
return re... |
2,640 | e3ee00efa0e929b87ca33b79dc6a6064b8758d4a | from django.conf.urls import url
from . import views
from .HouseView import CreateHouseView
app_name = 'voronoi'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^search/$', views.search, name='search'),
url(r'^house/create/$', CreateHouseView.as_view(), name='create'),
#url(r'^get_search... |
2,641 | 1552d862d3b9df45eda8c08256e8b4437ab08740 | from flask import Flask,request,Response
from spamapp.spam import SpamIdentify
from json import dumps,loads
app = Flask(__name__)
spam = SpamIdentify()
@app.route("/",methods=['GET'])
def home():
return Response(response=dumps({"msg":"App successfull"}), status=200, mimetype='application/json')
@app.route("/spam... |
2,642 | 2a4f57cd0fc1c50cba06c285849432c6f71f28e2 | import json
import os
import sys
"""
Course: cmps 4883
Assignemt: A03
Date: 2/10/19
Github username: acdczlc
Repo url: https://github.com/acdczlc/4883-SWTools-Conley
Name: Zac Conley
Description:
Calculates all stats for questions about stats
"""
##############################################################
# Mos... |
2,643 | 40ac3292befa2354878927ada0e10c24368a9d73 | import cv2
import numpy as np
cap = cv2.VideoCapture("./vStream.h264")
count = 0
while True:
ret, frame = cap.read()
if ret:
print("Decoded frame")
# cv2.imshow("frame", frame)
cv2.imwrite("fr_"+str(count)+".png", frame)
count += 1
else:
print("Couldn\'t decoded fra... |
2,644 | de3eaa5823fb396050527c148273c30bed6ce8ca |
def drive(carspeed):
if carspeed>200:
print("very fast")
elif carspeed>100:
print("toofast")
elif carspeed>70 and carspeed<80:
print("optimal speed")
else:
print("below speed limit")
print(drive(234))
print(drive(34))
drive(134)
#how none will be removed?
def compare(a):
if a>11:
print("big")
elif a==1... |
2,645 | 0774bad4082e0eb04ae3f7aa898c0376147e9779 | from models.bearing_registry import BearingRegistry
from models.faction import Faction
from models.maneuver import Maneuver
import time
class Activation:
"""
This class represents the Activation phase of a turn
"""
def __init__(self, game):
"""
Constructor
game: Th... |
2,646 | 5dfe86d654e4184bab4401f8b634326996e42e9c | """
Naive Bayes Class
- Bernoulli Naive Bayes
- Multinomial Naive Bayes
- Gaussian Naive Bayes
Arthor: Zhenhuan(Steven) Sun
"""
import numpy as np
class BernoulliNB:
def __init__(self, k=1.0, binarize=0.0):
# Laplace Smoothing Factor
self.K = k
# the degree... |
2,647 | 6cc56f73e58366a3906da537cc27fdd5a066ee34 | from django.conf.urls import url
#from .views import CommandReceiveView
from .views import index, send_message
urlpatterns = [
#url(r'^bot/(?P<bot_token>.+)/$', CommandReceiveView.as_view(), name='command'),
url(r'^send_message$', send_message, name='send_message'),
url(r'^$', index, name='index'),
]
|
2,648 | 1b3e64be988495454535ca96c7a1b6c20aa27076 | '''
A empresa Tchau de telefonia cobra:
-Abaixo de 200 minutos, R$ 0,20 por minuto
-Entre 200 e 400 minutos, R$ 0,18 por minuto
-Acima de 400 minutos, R$ 0,15 por minuto
- Bonus: - Acima de 800 minutos, R$ 0,08
Calcule a conta de telefone
'''
minutos = int(input('Minutos utilizados: '))
if minutos > 800:
total ... |
2,649 | 02bc97b963b970993fc947cfa41c73230dd4d9e4 | import swipe
def scheduleMultipoint(driver):
driver.find_element_by_id('com.dentist.android:id/calendarBt').click()
driver.find_element_by_id('com.dentist.android:id/addIb').click()
def time(driver):#就诊时间
driver.find_element_by_id('com.dentist.android:id/cureHourLl').click()#就诊时间
drive... |
2,650 | fb4818e742ed3c7d131c426811f839dbe70f03de | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from customer_support.views import update_existing_subscriber, \
add_new_subscriber
from .views import (EditSubscriberView,
DeActivateSubscriberView,
ReActivateSubscriberView,
SupportSub... |
2,651 | 1c979d505b58025aae74865d6556c726ed3f0769 | # Generated by Django 2.2.15 on 2020-09-16 03:20
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.db.models.fields
class Migration(migrations.Migration):
dependencies = [
('api', '0005_cashiershift_couriershift_couriershiftexpenses_... |
2,652 | 668fe3d561d94be73f2f721fac89e9e25005769b | import socket
import threading
#WebSocket Server Address
WS_ADDR = ("127.0.0.1",9876)
def ws_handler(sock,addr):
print 'ws handshaking...'
print 'connected...'
print 'closing...'
def websocket_server():
print 'listening for a WS connection... '
svSock = socket.socket()
svSock.setsockopt(soc... |
2,653 | ecc351cf95254e0bbc5021eff11c500fa0950bd3 | from bs4 import BeautifulSoup
from pprint import pprint
from scraper.sas.sas_models import SASEvent, SASCategory, SASCategoryStage, SASEventStage
from scraper.base_models.models import Event, Category, CategoryStage, EventStage, Participant, Result
from scraper.sas.sas_config import DESTINATION_URL, MTB_EVENT_TYPE, YE... |
2,654 | 48a4331e4b26ea81f1c52ae76db1e92a57cb378c | from django.urls import path
from .views import *
from .utils import *
app_name = 'gymapp'
urlpatterns = [
# CLIENT PATHS ##
# CLIENT PATHS ##
# CLIENT PATHS ##
# CLIENT PATHS ##
# general pages
path('', ClientHomeView.as_view(), name='clienthome'),
path('about/', ClientAboutView.as_v... |
2,655 | 753cc532e4d049bacff33c97de4d80bb9ab8ece8 | # Head start.
# ask me for this solution: 6cb9ce6024b5fd41aebb86ccd40d8080
# this line is not needed, just for better output:
from pprint import pprint
# just remove the top line
def count_or_add_trigrams(trigram, trigrams_so_far):
'''
Takes a trigram, and a list of previously seen trigrams
and ... |
2,656 | 4b255b648f67e6bcc30eecc7975bbb1a356b2499 | #到达终点的最小步数 leetcode原题 754 https://leetcode.com/problems/reach-a-number/solution/
# 分情况讨论:到target与到abs(target)的情况是一样的
# 1. total = 1+2+...+k,求total刚好大于等于n的k,可知到达target至少要用k步,此时超出d=total-k
# 2. 如果d为偶数,则只需将d/2步反向即可,k步即可到达target
# 3. 如果d为奇数,则k步不可能到达,因为任何反转都会改变偶数距离,不可能消去d,则再走一步判断d+k+1是否为偶数
# 4. 如果为偶数,说明k+1步可到
# 5. 如果d+k+1为奇... |
2,657 | 6efd22feb4f96de74633276b1ec8550f8d853075 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
def test_register_new_accont(self):
cos = self.cos
cos.get("https://wizzair.com/pl-pl#/")
cos.find_elements_by_class_name('navigation__button navigation__button--simple').click()
cos.find_elements_by_class_name('content__lin... |
2,658 | 5ee667e8394ccacf83bfe4baec228373619b4edb | import AVFoundation
from PyObjCTools.TestSupport import TestCase
class TestAVAssetSegmentReport(TestCase):
def test_enum_types(self):
self.assertIsEnumType(AVFoundation.AVAssetSegmentType)
def test_constants(self):
self.assertEqual(AVFoundation.AVAssetSegmentTypeInitialization, 1)
sel... |
2,659 | 278f0ece7cc2c7bb2ec1a3a2a7401bf3bc09611d | #!/usr/bin/env python
# Copyright (c) 2016, SafeBreach
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of cond... |
2,660 | ec2be72f81d260c491cdc31b68b34401fb49b91e | import copy
import numpy as np
from PySide2.QtCore import QItemSelectionModel, QObject, Signal
from PySide2.QtWidgets import (
QComboBox, QLineEdit, QSizePolicy, QTableWidgetItem
)
from hexrd.constants import chargestate
from hexrd.material import Material
from hexrd.ui.periodic_table_dialog import PeriodicTabl... |
2,661 | 254f34c923d49374e09b579c5bc1b17b8c69c0e4 | from dataclasses import dataclass
from models.user import User
class Customer(User):
def __init__(self, first_name: str, last_name: str, user_name: str, email: str, password: str):
super(Customer, self).__init__(first_name, last_name, user_name, email, password)
# def __str__(self):
# return... |
2,662 | ec9de8d54113806ab327f05e077edefa74258adb | #!/usr/bin/env python
import re
class Solution:
def __new__(self, p):
nr_counts, nr_consonants, replaced = self.count_vowels_consonants(self, p)
inversed = ''.join(c.lower() if c.isupper() else c.upper() for c in p)
replaced_by_ = p.replace(' ' ,'-')
combined_queries = str(nr_counts) + ' ' + str(nr_conso... |
2,663 | 4ff7e83c6e85a041578a8b3471cbbb7e0c2543e6 | # 1-[2-3-4-5]-1
# 순열로 돌리고, 백트래킹으로 걷어내기
def DFS(idx, cost, cur_loc):
global min_cost
if min_cost < cost: return
if idx == N and arr[cur_loc][0]:
if min_cost > cost + arr[cur_loc][0]:
min_cost = cost + arr[cur_loc][0]
return
for i in range(1, N):
if way[i] or not arr[c... |
2,664 | 7e7a50cb8e66a71c1df2d61241f8a55c042b7d59 | import os
import sys
import pytest
def run_test(file_name, capture_stdout=True, allure_dir=None):
cmd = [
file_name, "-vvv",
]
if capture_stdout:
cmd.append("-s")
test_name = os.path.splitext(os.path.basename(file_name))[0]
alluredir = os.path.normpath("%s/%s/" % (allure_dir or "... |
2,665 | 2b796fb99e4607d310a533e8d9897100c4df087d | class ListNode:
def __init__(self,listt,node,g,h):
self.node_list = []
for element in listt:
self.node_list.append(element)
self.node_list.append(node)
self.g=g
self.f = int(g)+int(h);
self.ID = node
def is_Goal(self,complete_nodes):
... |
2,666 | b324c520400f04719b17121b0b4c2d23915e8841 | 5 1
6 1x
1112#Desember@@@@@ |
2,667 | eb6a4170e5427f10eda4d650996c2cbd8a34ca21 | Relevance
Thus, designing an automatic MWP solver, with semantic understanding and
inference capability, has been considered as a crucial step towards general AI.
Solving a math problem manually involves too many steps. So MWP will reduc
Attachment final.pdf added.Conversation opened. 1 read message.
Skip ... |
2,668 | bbe7df31a44ccf51c305cd620dc7c4155b7e1a97 | def get_bios_boot_order(self):
result = {
}
boot_device_list = []
boot_device_details = []
key = 'Bios'
bootsources = 'BootSources'
response = self.get_request((self.root_uri + self.systems_uri))
if (response['ret'] is False):
return response
result['ret'] = True
... |
2,669 | 22c0b8c8d598bb91bb2333343aad285bbcb4ee5b | import logging
import search_yelp
import uuid
from apiclient import errors
from google.appengine.api import taskqueue
def insert_worker(mirror_service, food_type=None):
logging.info('zip1 food_type %s' % food_type)
try:
location = mirror_service.locations().get(id='latest').execute()
latlong... |
2,670 | 5e2a8e95af88a582b6e760a53dfd41f880d66963 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Admin.ui'
#
# Created by: PyQt5 UI code generator 5.12
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from qtpandas.views.DataTableView import DataTableWidget
from qtpandas.models.DataFra... |
2,671 | 0846f73482ad86158c3f4e37713d6d965e21d796 | """This file parses vbulletin forums"""
import re
import logging
from BeautifulSoup import BeautifulSoup as bs
import imaget
import pdb
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
date_marker = ["<!-- status icon and date -->", "<!-- / status icon and date -->"]
message_marker = ["<!-- messa... |
2,672 | c7d9bbdff9148c5d928de66f4406ee8b4e1bcdac | """
Card rarity parameters
"""
from typing import List, Optional
from django.db.models.query import Q
from cards.models.rarity import Rarity
from cardsearch.parameters.base_parameters import (
OPERATOR_MAPPING,
OPERATOR_TO_WORDY_MAPPING,
CardTextParameter,
CardSearchContext,
ParameterArgs,
Que... |
2,673 | a35004e2b306ba1a8649ce66a1612f63a2b6bf39 | import hashlib
from django.conf import settings
from django.core import mail
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.crypto import get_random_string
def hexdigest_sha256(*args):
r = hashlib.sha256()
for arg in args:
r.... |
2,674 | 7994d9605c8654053c9a85f8d37983da04f8003a | from datetime import datetime, timedelta
import os
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators import (StageToRedshiftOperator, LoadFactOperator,
LoadDimensionOperator, DataQualityOperator)
from helpers import SqlQueries
# AW... |
2,675 | d86fd2e6ef5dab4444772192471538842112b3fd | from skimage import data, filters, measure, exposure
from skimage.filters import threshold_mean
from skimage.transform import resize
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pyfits as pf
import time
import numpy as np
import healpy as hp
from healpy.projector import CartesianProj
f... |
2,676 | f3e654a589cc1c16b36203dd358671d0426556e6 | import os
import requests
from pprint import pprint as pp
from lxml import html
from bs4 import BeautifulSoup
from dotenv import load_dotenv
import datetime
load_dotenv()
class PrometeoAPI:
def __init__(self, user, pwd):
self.base_url = 'https://prometeoapi.com'
self.session = requests.Session()... |
2,677 | e89ca4907373318bd55d0833730a30d981414992 | # =============================================================================
# ######################## Creator: Rhys Aeron Williams #######################
# ######################## Last update: 14th March 2019 #######################
# =============================================================================
... |
2,678 | d025b0719c6eecdfccb2e39a58af7842f4229c72 | from abc import ABC, abstractmethod
class Book:
def __init__(self, title: str, content: str):
self.title = title
self.content = content
class Formatter(ABC):
@abstractmethod
def format(self, book: Book):
pass
class TitleFormatter(Formatter):
def format(self, book: Book) -> ... |
2,679 | c65755d7a58c1cda7d6eea83876e0522a7ca9c74 | # 拆包
t1 = (4,7,3)
# a,b=t1 # ValueError:too many values to unpack(拆包) (expected 3, got 2)
a,b,c = t1
print(a,b,c)
a = t1
print(a)
# x,y,z = (6,) # ValueError: not enough values to unpack (expected 3, got 1)
# s1 = 'hello'
# s2 = s1
# 变量个数与元祖个数不一致
t1 = (12,23,42,12,43)
a,*_,c = t1
print(a,c,_)
a,c,*_ = t1
p... |
2,680 | b10badc172be119be5b2ab8ccc32cc95a0ed1e7a | import cv2
import pdb
import skvideo
import numpy as np
import pandas as pd
from tqdm import tqdm
from harp import fdops
from word2number import w2n
from harp.vid import VidReader
class RegPropData:
"""
Processes region proposal data.
"""
_df = None
props = None
"""Dictionary containing regio... |
2,681 | dd8f4b08b88d487b68e916e9f92c08c9c0bc39da | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
# 连接到db文件
conn = sqlite3.connect('app.db')
# 创建一个Cursor:
cursor = conn.cursor()
# 查询所有表名:
cursor.execute("select name from sqlite_master where type = 'table' order by name")
print("Tables name:", cursor.fetchall())
# 查询表user的结构:
cursor.ex... |
2,682 | 0f54853901a26b66fe35106593ded6c92785b8db | import asyncio
import logging
from datetime import datetime
from discord.ext import commands
from discord.ext.commands import Bot, Context
from humanize import precisedelta
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy_utils import ScalarListException
from config import CONFIG
from models import Reminder... |
2,683 | 23b2cc5b561a11ae7757a281a141491d5b7e23ca | from discord.ext import commands
def is_owner():
async def predicate(ctx):
return ctx.author.id == 98208218022428672
return commands.check(predicate)
class Staff(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(
name='stop',
aliases=['shutdow... |
2,684 | 05e468c2f64e33d6b390f681314ed7961bd4def7 | import time
import datetime
import math
import os
import random
import logzero
import logging
from logzero import logger
from sense_hat import SenseHat
import ephem
anyException = False
# program Time is here for easy acces (in minutes)
programTime = 175
# 2:55 min of runtime
# _________________________... |
2,685 | 0412369f89842e2f55aa115e63f46a1b71a0f322 | s=int(input())
print(s+2-(s%2)) |
2,686 | 268a8252f74a2bdafdadae488f98997c91f5607c | import os
from unittest import TestCase
class TestMixin(TestCase):
@classmethod
def setUpClass(cls):
cls.base_dir = os.path.dirname(os.path.abspath(__file__))
cls.fixtures_dir = os.path.join(cls.base_dir, 'fixtures')
cls.bam_10xv2_path = os.path.join(cls.fixtures_dir, '10xv2.bam')
... |
2,687 | 44f18d7e7713073c27fec38f0b847803eceefbc9 | import random
print(random.choice(['python','c++','java']))
print(random.choice((1.1,-5,6,4,7)))
|
2,688 | b9678b447bc6e7c4e928ffa6b8cd58639e41a801 | """
Author: Alan Danque
Date: 20210323
Purpose:Final Data Wrangling, strips html and punctuation.
"""
from sklearn.tree import export_graphviz
import pydot
import pickle
from pathlib import Path
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.ensemble import ... |
2,689 | 2b73c4e07bba7ed5c89a31ebd45655eaa85dcdcc |
__all__ = '''
calc_common_prefix_length
'''.split()
import operator
import itertools
def calc_common_prefix_length(lhs_iterable, rhs_iterable, /, *, __eq__=None):
if __eq__ is None:
__eq__ = operator.__eq__
idx = -1
for a, b, idx in zip(lhs_iterable, rhs_iterable, itertools.count(0)):
... |
2,690 | 7383ae97d6a1368896d05d0cafc9846c24004701 | """Testing data storage functionality in gludb.simple (see simple_tests.py for
testing of the rest of gludb.simple functionality)"""
import unittest
import datetime
import time
import gludb.config
from gludb.versioning import VersioningTypes
from gludb.data import orig_version
from gludb.simple import DBObject, Fiel... |
2,691 | c8bb6ead7e305f466e24b47811d6ed38c8cfec0a |
from oscar.app import Shop
from apps.catalogue.app import application as catalogue_app
class BaseApplication(Shop):
catalogue_app = catalogue_app
application = BaseApplication()
|
2,692 | 355d60300cbbed817b4512e9b02cc4dd53d1293e | friends = ["Rolf", "Bob", "Anne"]
print(friends[0])
print(friends[1])
print(len(friends))
new_friends = [
["Rolf", 24],
["Bob", 30],
["Anne", 27],
["Charlie", 25],
["Jen", 25],
["Adam", 29]
]
print(friends[0][0])
friends.append("Jen")
print(friends)
new_friends.remove(["Anne", 27])
print(new... |
2,693 | d96038a715406388b4de4611391dee18fc559d5a | import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import pandas as pd
import time
from urllib.request import Request
import requests
import json
import re
import sys
def compare(mystring):
def usd_to_ngn():
print("Getting USD to NGN Rate")
r... |
2,694 | 180d28ac77b6ff4488b3fd9c17a9ee4571e33631 | import math
#variables for current GPS Lat / Lon Readings
currentLat = 41.391240
currentLon = -73.956217
destLat = 41.393035
destLon = -73.953398
#variables for current UTM coordinates
currentX = 587262
currentY = 4582716
destX = 587499
destY = 4582919
#declination angle based on geographic location
#see #https://ww... |
2,695 | 382a3b8bcd07c7098cecf2b770e46dfff50eeb98 | #####################
# Aufgabe 2, 13.7 #
# v1.0 #
# baehll #
# 04.05.2018 #
#####################
class Pinnwand:
def __init__(self):
self.__zettel = []
def hefteAn(self, notiz):
#Analyse des Textes
prio = notiz.count("!")
self.__zettel.ap... |
2,696 | ec70fb9119b430dcd36549f2fac8e5e0a0e1bb00 |
from django.http import HttpResponsePermanentRedirect
from django.urls import is_valid_path
from django.utils.deprecation import MiddlewareMixin
from django.utils.http import escape_leading_slashes
class AppendSlashMiddleware(MiddlewareMixin):
response_redirect_class = HttpResponsePermanentRedirect
def proc... |
2,697 | b094693b11fdc4f5fbff30e79a9f82d40104611d | from time import time
class Task:
def __init__(self, f, ready: float):
self._f = f
self._ready = ready
def set_ready(self, ready: float) -> None:
self._ready = ready
def get_ready(self) -> float:
return self._ready
def __call__(self) -> None:
self._f()
de... |
2,698 | 8040b47dc3fd6b03432f64d7fb8a4267cc94ac9a | import caffe
import numpy as np
class PyLayer(caffe.Layer):
def setup(self, bottom, top):
if len(bottom) != 2:
raise Exception("Need two inputs to compute distance")
def reshape(self, bottom, top):
if bottom[0].count != bottom[1].count:
raise Exception("Inputs must have the same dimension")
... |
2,699 | 8d6e4d06e390b4a45e576239189745c2e37217c5 | import json
from datetime import datetime, timedelta
from itertools import product
from django.db.models import QuerySet
import pytz
from model_mommy import mommy
from ...views import get_authors, get_featured_challenges, get_term_of_user
class TestNonMiscView:
"""Test for non view functions in ideax.views (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.