index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
5,300 | 39f1595374147c71bc2d4c945a0f1149891f1883 | import cx_Oracle
import datetime
SDATE = '01.01.2014'
FDATE = '01.01.2020'
#p.PRESZAB,
#GDR_RATE.RFLUID,
#p.NRES
#join GDR_RATE on GDR_RATE.IDWELL = p.IDWELL and GDR_RATE.DTBGN = p.DTBGN and GDR_RATE.NRES = p.NRES)
pbu_query_raw = f"""
select
WELLNAME,
DTBGN,
DPDEVICE,
(TVDSS-(MD - DPDEVICE)*... |
5,301 | 97afa67cbe20900e2388994481abebe772e22818 | import pandas as pd
triples = pd.read_csv("SollTripel.csv", sep=",", skip_blank_lines=True, skipinitialspace=True)
triples.columns = ["triple", "found"]
triples = triples["#" not in triples.triple]
print(triples) |
5,302 | f52bac3e658a34b82721746364fab11d25d470c4 | from .VimaptException import VimaptException
class VimaptAbortOperationException(VimaptException):
pass
|
5,303 | 251d589a5815d77d2bc375d8d4a7d41e79a2a5cd | # Mostra entre as 7 pessoas, quantas pessoas são maiores de idade.
num1 = 0
for c in range(0,7):
pe1 = int(input('Digite o ano de nascimento: '))
pe1 = 2019 - pe1
if pe1 >= 21:
num1 = num1 + 1
print(f'Entre as 7 pessoas, {num1} pessoas são maiores de idade.') |
5,304 | 941dac77fe60081ffa113c437a356d59837f5883 | from collections import OrderedDict as odict
from vent.gui import styles
MONITOR = odict({
'oxygen': {
'name': 'O2 Concentration',
'units': '%',
'abs_range': (0, 100),
'safe_range': (60, 100),
'decimals' : 1
},
'temperature': {
... |
5,305 | 8247b045a5aed4d0f3db6bc2c0edd985f2c4ba30 | import os
def get_os_env_value(key):
return os.getenv(key)
def get_mysql_uri(user, password, host, database):
return f'mysql+pymysql://{user}:{password}@{host}/{database}'
MASTER_MYSQL_DATABASE_USER = get_os_env_value('MASTER_MYSQL_DATABASE_USER')
MASTER_MYSQL_DATABASE_PASSWORD = get_os_env_value('MASTER_... |
5,306 | 59de17ea4e714e17e3a7dd966bd0d93ba73f4503 | #!/usr/bin/env python
from pymongo import GEO2D
from GlobalConfigs import eateries
eateries.create_index([("eatery_coordinates", GEO2D)])
eateries.ensure_index([("eatery_coordinates", pymongo.GEOSPHERE)])
for e in eateries.find({"eatery_coordinates": {"$near": [latitude, longitude]}}).limit(5):
print e.get... |
5,307 | 4dea0967a0ee3e9eb3b46145739dfeb233f3a120 | '''
Trolls are attacking your comment section!
A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat.
Your task is to write a function that takes a string and return a new string with all vowels removed.
For example, the string "This website is for... |
5,308 | 5ab20c1cd2dc0d0ad881ee52008d00c2317084f9 | from django.db import models
# Create your models here.
class Position(models.Model):
title = models.CharField(max_length=50)
def __str__(self):
return self.title
class Employee(models.Model):
nom = models.CharField(max_length=100)
prenom = models.CharField(max_length=100)
age= models.Cha... |
5,309 | d5acda0d5d066d381a7f6310eb4fe6280d7e84de | import unittest
from collections import Counter
class Solution(object):
def findOriginalArray(self, changed):
"""
:type changed: List[int]
:rtype: List[int]
"""
n = len(changed)
if n % 2 != 0:
return []
freq = Counter(changed)
changed.s... |
5,310 | 0b3d6339faf9d66d4e1338599e4784fac0f63d3f | def solution(citations):
# 사이테이션을 정렬
citations.sort()
#
for i in range(len(citations)):
if citations[i] >= len(citations) - i:
return len(citations)-i
print(solution([3,0,6,1,5])) |
5,311 | 12f035962925c5380c782e8fad23f16fe9fb9435 | #cerner_2^5_2019
#Mason Seeger submission 1
from random import randint as r
import operator as o
#Only works with valid integers. A function for quick math brain training.
def randomMath():
correct = 0
while(correct<10):
str_ops = ['+', '-', '*', '/', '%']
ops = {'+': o.add, '-': o.sub, '*': o... |
5,312 | dc13ca17bff8e2a5254c7758bd7274926bafd454 | from dataclasses import dataclass
from datetime import date
@dataclass
class Book:
id: int
title: str
author: str
genre: str
published: date
status: str = 'Available'
def __str__(self):
return f'{self.id}: {self.title} by {self.author}'
def get_more_information(self):
... |
5,313 | bc53af24bb46d2be3122e290c4732b312f4ebdf5 | from get_info import parse_matches as pm
def all_match_data(year):
"""
Searches through the parse_matches data for all games in a specific season prints them out with a game ID and
returns the data in a list to the main program
:param year: Specific format YYYY between 2008 - 2017
:return: year_ma... |
5,314 | 422873f89468b1faabed96f72f463b6294b85276 | # Generated by Django 3.0.5 on 2020-05-12 13:26
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='idcard',
fields=[
('id', models.AutoField(a... |
5,315 | 97e7ca02d85267492a0dcbbda9d8754a0a3735a5 | from core.detector import Detector
from utils.augmentations import *
from torchvision.transforms.transforms import Compose
from config.mask_config import *
from config.train_config import model_info
np.random.seed(3)
colors = np.random.randint(128, 256, (100, 3))
def to_image(det):
size = 512
val_trans = [... |
5,316 | 084579152a2cc7feb2c31e0209ce1e32f4905d81 | import chars2vec
import sklearn.decomposition
import matplotlib.pyplot as plt
import csv
# Load Inutition Engineering pretrained model
# Models names: 'eng_50', 'eng_100', 'eng_150' 'eng_200', 'eng_300'
from sklearn.cluster import KMeans
c2v_model = chars2vec.load_model('eng_50')
words=[]
etichette=[]
with open('da... |
5,317 | f225fbf363f1b170704418ed339f2e57ca790975 | from django import forms
from django.utils.translation import gettext_lazy as _
import django_filters
from elasticsearch_dsl.query import Q
class BaseSearchFilterSet(django_filters.FilterSet):
query_fields = ["content"]
q = django_filters.CharFilter(
method="auto_query",
widget=forms.TextInp... |
5,318 | e3b8bec0cc7df217052a3182f9a862f0e3622afd | #!python
import pdb
import argparse
import os
import re
import sys
import string
from utilpack import path
from subprocess import Popen
from subprocess import PIPE
def popen(cmd):
spl = cmd.split()
return Popen(spl, stdout=PIPE).communicate()[0]
def debug (s):
s
dists = 0
def get_setup_ini (setup_in... |
5,319 | 833053a5a75636267feaad5ddaa21dce1de34038 | #!/usr/bin/env python
"""
maskAOI.py
Dan Fitch 20150618
"""
from __future__ import print_function
import sys, os, glob, shutil, fnmatch, math, re, numpy, csv
from PIL import Image, ImageFile, ImageDraw, ImageColor, ImageOps, ImageStat
ImageFile.MAXBLOCK = 1048576
DEBUG = False
AOI_DIR='/study/reference/public/IAP... |
5,320 | faa53db9dd581b6508fb9e4042ec86ebaf850e60 | from sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score
print(accuracy_score(true_labels, guesses))
print(recall_score(true_labels, guesses))
print(precision_score(true_labels, guesses))
print(f1_score(true_labels, guesses))
from sklearn.metrics import confusion_matrix
print(confusion_mat... |
5,321 | d5a31e53444e2efa2eb972f1152b6d3e37d5ab79 | aminotable = [
['Ile' , 'AUU','AUC','AUA'], #0
['Leu' , 'CUU','CUC','CUA','CUG','UUA','UUG'], #1
['Val' , 'GUU','GUC','GUA','GUG'], #2
['Phe' , 'UUU','UUC'], #3
['Met' , 'AUG'], ... |
5,322 | 436b89b91aed14525f847e6488b452b7ca0e1b70 | from enum import Enum
class AggregationTypes(Enum):
NO_AGG = 'NO-AGG'
STATIC = 'STATIC'
SUB_HOUR = 'SUB-HOUR'
DYNAMIC = 'DYNAMIC'
|
5,323 | e2840eb1b0d731d6b0356835ba371d05ba351ff6 | """APP Cloud Connect errors"""
class CCEError(Exception):
pass
class ConfigException(CCEError):
"""Config exception"""
pass
class FuncException(CCEError):
"""Ext function call exception"""
pass
class HTTPError(CCEError):
""" HTTPError raised when HTTP request returned a error."""
de... |
5,324 | ddf074e400551d2c147d898fe876a31d13a72699 | class Fail(Exception):
def __init__(self, message):
super().__init__(message)
class Student:
def __init__(self, rollNo, name, marks):
self.rollNo = rollNo
self.name = name
self.marks = marks
def displayDetails(self):
print('{} \t {} \t {}'.format(self.name, self.ro... |
5,325 | 92f4f1c8a4e04b07ed7c05d5bb733c0b9c28bd05 | # i change it for change1
# change 1.py in master
i = 1
# fix bug for boss
|
5,326 | fc2afc99dc754b58c36bc76c723727337851cc3e | from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse
# Create your views here.
def check(request):
if not request.user.is_authenticated:
return redirect('/auth/login/')
else:
return redirect('/worker/')
... |
5,327 | a721adaaa69bf09c2ea259f12bea05515c818679 | # TrackwayDirectionStage.py
# (C)2014-2015
# Scott Ernst
from __future__ import print_function, absolute_import, unicode_literals, division
from collections import namedtuple
import math
from pyaid.number.NumericUtils import NumericUtils
from cadence.analysis.CurveOrderedAnalysisStage import CurveOrderedAnalysisSta... |
5,328 | 4a5185fac7d6c09daa76b5d0d5aee863028a6bce | from functools import partial
import torch
from torch import nn
from src.backbone.layers.conv_block import ConvBNAct, MBConvConfig, MBConvSE, mobilenet_v2_init
from src.backbone.mobilenet_v2 import MobileNetV2
from src.backbone.utils import load_from_zoo
class MobileNetV3(MobileNetV2):
def __init__(self, residu... |
5,329 | c02af2ecd980da4ceff133c13072ad7c6b724041 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from hilma import Mesh, loadPly, savePly
mesh = Mesh()
loadPly("head.ply", mesh)
verts = []
faces = []
edges = []
uvs = ... |
5,330 | 666e839b4d66dc4eede4e7325bfd4f4b801fd47d | from django.urls import path, re_path
from app.views import UploaderAPIView, TeacherListAPIView, TeacherDetailAPIView
app_name = "directory"
urlpatterns = [
re_path(r"^directory/uploader/?$", UploaderAPIView.as_view(), name="teacher_uploader"),
re_path(r"^directory/teachers/?$", TeacherListAPIView.as_view(), ... |
5,331 | 94264e121bb31a08cbd9766be1ff16173d2838ed | import pandas
class _RegressionModelTable(object):
def __init__(self, regression_models, function_to_evaluate_model=None, function_to_select_model=None):
if not isinstance(regression_models, list):
regression_models = [regression_models]
self._check_model_inputs(regression_models, fu... |
5,332 | 7f58179efecd5a0d691a5c6d83b808f2cd2fcba3 | from RestClient4py.client import RestClient
from API_Wrap import util
import os
import json
kakao_native_app_key, kakao_rest_api_key, kakao_javascript_key, kakao_admin_key = util.kakao_auth()
client = RestClient()
client.set_header("Authorization", "KakaoAK {}".format(kakao_rest_api_key))
client.set_header("Accept", ... |
5,333 | f494dc99febfad99b371d72f542556a9024bc27d | #
# Copyright (c) 2018-2020 by Kristoffer Paulsson <kristoffer.paulsson@talenten.se>.
#
# This software is available under the terms of the MIT license. Parts are licensed under
# different terms if stated. The legal terms are attached to the LICENSE file and are
# made available on:
#
# https://opensource.org/lice... |
5,334 | fc4cf800c663abf20bfba7fcc1032e09a992641b | __author__ = 'asistente'
#from __future__ import absolute_import
from unittest import TestCase
from selenium import webdriver
from selenium.webdriver.common.by import By
class FunctionalTest(TestCase):
def setUp(self):
self.browser = webdriver.Chrome("C:\\chromedriver\\chromedriver.exe")
self.b... |
5,335 | 34a523b31e5567d2a8aec95c5820792d1ae80892 | from django.db import models
# Create your models here.
from user.models import User
class Post(models.Model):
class Meta:
db_table = 'bl_post'
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=200, null=False)
pubdate = models.DateTimeField(null=False)
# 作者
... |
5,336 | 548eebb9628374df320021c714454e05d2c606c0 | from __future__ import absolute_import, print_function, division, unicode_literals
import tensorflow as tf
def get_encoder(conf):
if conf.encoder == 'linear':
model = tf.keras.Sequential([tf.keras.layers.Dense(conf.d_model * 2),
tf.keras.layers.ReLU(),
... |
5,337 | ed5ba72443b70c84941af3d112e0246cb3ae97d9 | ####################################
## Readable code versus less code ##
####################################
import threading
from web_server.general_api import general_api as api
logger = api.__get_logger('ConnTimeout.run')
class ConnTimeout(object):
def __init__(self, timeout, function, servers=5, args=[], ... |
5,338 | f23b002ec0eefa376890e255b1ac0137e3a1c989 | from django.urls import path
from player.views import (
MusicListView, MusicPlayView, MusicPauseView, MusicUnPauseView,
NextSongView, PreviousSongView
)
urlpatterns = [
path('list/', MusicListView, name="music_list"),
path('play/<str:name>/', MusicPlayView, name="play_music"),
path('pause/', Music... |
5,339 | b4a96d5df56acd545e9919e202c462ee710a0339 | #print pathToConnectionsList(['A','C','B','D','E'])
#['EA','CB','AC','BD', 'DE']
#print independantPathPieces()
#print pathToConnectionsList(pathGenerator())
#print geneFormatToPathSegmentsMini(['CD', 'AB', 'BE', 'EC']) #DA
#print independantPathPieces(['EAC', 'CBD', 'ACB', 'BDE', 'DEA'])
#print greedyCrossover(['EC', ... |
5,340 | 59b2c9d279168a806e59fb7529ab12d7b86107bc | # 213. 打家劫舍 II
# 你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋是紧挨着的。
# 同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。
# 给定一个代表每个房屋存放金额的非负整数数组,计算你 在不触动警报装置的情况下 ,能够偷窃到的最高金额。
class Solution:
# 86.24%, 15.46%
def rob(self, nums) -> int:
n = len(nums)
if n == 0:
... |
5,341 | a521befba58aa85c2fcfe6006db4b161123585f1 | # Copyright 2018-present Kensho Technologies, LLC.
from .utils import create_vertex_statement, get_random_date, get_uuid
EVENT_NAMES_LIST = (
"Birthday",
"Bar Mitzvah",
"Coronation",
"Re-awakening",
)
def _create_event_statement(event_name):
"""Return a SQL statement to create a Event vertex."""... |
5,342 | b0ab97f5c05cdeee4c01460109a76cef75ac72ce | print("Convertidor de pies y pulgadas a centímetros")
pies = float(input("Escriba una cantidad de pies: "))
pulgadas = float(input("Escriba una cantidad de pulgadas: "))
cm = (pies * 12 + pulgadas) * 2.54;
print("{} pies y {} pulgadas son {} cm".format(pies, pulgadas, cm))
|
5,343 | df1486afcc99e03510512ed6ed3e8b3471459d50 | import pkgutil
import mimetypes
import time
from datetime import datetime
from pywb.utils.wbexception import NotFoundException
from pywb.utils.loaders import BlockLoader
from pywb.utils.statusandheaders import StatusAndHeaders
from pywb.framework.basehandlers import BaseHandler, WbUrlHandler
from pywb.framework.wbre... |
5,344 | a179d3d2f04a101eaa60b5964c2b1cd77071633f | from envs import DATASET_FOLDER
from os.path import join
import json
import collections
from tqdm import tqdm
def add_space(context_list):
space_context = []
for idx, context in enumerate(context_list):
space_sent_list = []
sent_list = context[1]
if idx == 0:
for sent_idx, s... |
5,345 | 55c00ce4c1657dc5ce78e5eeccd8e9625c0590dc | import requests
import json
import logging
import time
from alto.server.components.datasource import DBInfo, DataSourceAgent
class CRICAgent(DataSourceAgent):
def __init__(self, dbinfo: DBInfo, name: str, namespace='default', **cfg):
super().__init__(dbinfo, name, namespace)
self.uri = self.ensu... |
5,346 | 10c9566503c43e806ca89e03955312c510092859 | import datetime
import json
import re
import time
import discord
from utils.ext import standards as std, checks, context, logs
DISCORD_INVITE = '(discord(app\.com\/invite|\.com(\/invite)?|\.gg)\/?[a-zA-Z0-9-]{2,32})'
EXTERNAL_LINK = '((https?:\/\/(www\.)?|www\.)[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6})'
EVE... |
5,347 | 0ad2e6d7e3fd61943fc1dfe6662110a6f48c1bd5 | from .parse_categories import extract_categories
from .parse_sections import extract_sections
from .utils import remove_xml_comments
def parse_page(page):
if 'redirect' in page.keys():
return
page_text = page['revision']['text']['#text']
page_text = remove_xml_comments(page_text)
title = pag... |
5,348 | 4d07795543989fe481e1141756f988d276f82c02 | """
7-4. Pizza Toppings: Write a loop that prompts the user to enter a series of
pizza toppings until they enter a 'quit' value. As they enter each topping,
print a message saying you’ll add that topping to their pizza.
"""
if __name__ == '__main__':
topping = None
while topping != "quit":
if topping:
... |
5,349 | 51bdbec732bebd73a84b52c6d1d39eead047d29e | from __future__ import absolute_import
import unittest
import yaml
import os
from bok_choy.web_app_test import WebAppTest
from .pages.job_config_history_subpage import JobConfigHistorySubPage
class TestJobConfigHistory(WebAppTest):
def setUp(self):
super(TestJobConfigHistory, self).setUp()
config_... |
5,350 | 2ad1b44027b72499c1961f2d2b1c12c356c63d2b | import numpy,math,random
from scipy.io.wavfile import write
notes=[('c',32.7),('c#',34.65),('d',36.71),('d#',38.89),('e',41.2),('f',43.65),
('f#',46.25),('g',49),('g#',51.91),('a',55),('a#',58.27),('b',61.47)]
#notes={'c':32.7,'c#':34.65,'d':36.71,'d#':38.89,'e':41.2,'f':43.65,'f#':46.25,
# 'g':49,'g#':51.91,'a... |
5,351 | ec39dae7217ddc48b1ab5163d234542cb36c1d48 | # Generated by Django 3.1.1 on 2020-10-14 16:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Store', '0004_remove_product_mcat'),
]
operations = [
migrations.RemoveField(
model_name='categ... |
5,352 | f4ca7f31000a1f649876b19ef937ece9958dd60f | def maior(a,b):
if a > b:
return a
else:
return b
a = int(input("Digite o 1 valor: "))
b = int(input("Digite o 2 valor: "))
print(maior(a,b))
|
5,353 | 5c06229f8e80a7225620f25941cc5276a9021e53 | #===============================================================================
# @author: Daniel V. Stankevich
# @organization: RMIT, School of Computer Science, 2012
#
#
# This package contains representations of the following models:
# 'Particle' - an atomic element
# 'Swarm' - a set of p... |
5,354 | fd7961d3a94b53ae791da696bb2024165db8b8fc | import pandas as pd
import csv
import numpy as np
import matplotlib.pyplot as plt
#import csv file with recorded left, right servo angles and their corresponding roll and pitch values
df = pd.read_csv('C:/Users/yuyan.shi/Desktop/work/head-neck/kinematics/tabblepeggy reference tables/mid_servo_angle_2deg_3.csv') ... |
5,355 | 8e05b2723d8c50354e785b4bc7c5de8860aa706d | import torch
import torchvision
from torch import nn
def get_resnet18(pre_imgnet = False, num_classes = 64):
model = torchvision.models.resnet18(pretrained = pre_imgnet)
model.fc = nn.Linear(512, 64)
return model
|
5,356 | 4a13a0d7aa2371d7c8963a01b7cc1b93f4110d5e | # 백준 문제(2021.5.22)
# 10039번) 상현이가 가르치는 아이폰 앱 개발 수업의 수강생은 원섭, 세희, 상근, 숭, 강수이다.
# 어제 이 수업의 기말고사가 있었고, 상현이는 지금 학생들의 기말고사 시험지를 채점하고 있다.
# 기말고사 점수가 40점 이상인 학생들은 그 점수 그대로 자신의 성적이 된다.
# 하지만, 40점 미만인 학생들은 보충학습을 듣는 조건을 수락하면 40점을 받게 된다.
# 보충학습은 거부할 수 없기 때문에, 40점 미만인 학생들은 항상 40점을 받게 된다.
# 학생 5명의 점수가 주어졌을 때, 평균 점수를 구하는 프로그램을 작성... |
5,357 | d6c06a465c36430e4f2d355450dc495061913d77 | import os
import sys
import glob
import argparse
import shutil
import subprocess
import numpy as np
from PIL import Image
import torch
import torch.backends.cudnn as cudnn
import torch.nn.functional as F
from torch.autograd import Variable
from torchvision.utils import save_image
sys.path.append(os.pardir)
from model... |
5,358 | bc0846397a5ad73b1c4b85e12864b27ef4fd08d7 | import ctypes
import win32con
import request_spider
from selenium_tickets_spider import *
from threading import Thread
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import sys, time, re
import datetime
SESSION_DATA = False
SHOW_S_P = False
class Wor... |
5,359 | 849343561dd9bdcfc1da66c604e1bfa4aa10ddf3 | # bot.py
import os
import sqlite3
import json
import datetime
from dotenv import load_dotenv
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from cogs.utils import helper as h
intents = discord.Intents.default()
intents.members = True
load_dotenv()
TOKEN = os.getenv('DISCORD_T... |
5,360 | df4c03d9faedf2d347593825c7221937a75a9c10 | from api import *
version_api = api(0)
def is_bad_version(v):
return version_api.is_bad(v)
def first_bad_version(n):
# -- DO NOT CHANGE THIS SECTION
version_api.n = n
# --
api_calls_count = 0
left, right = 1, n
while left < right:
mid = (left + right) // 2
is_bad = is_bad_versio... |
5,361 | c0218acadb9e03359ac898cf3bb4898f516400e5 | from setuptools import setup
setup(name='google-drive-helpers',
version='0.1',
description='Helper functions for google drive',
url='https://github.com/jdoepfert/google-drive-helpers',
license='MIT',
packages=['gdrive_helpers'],
install_requires=[
'google-api-python-client... |
5,362 | 8af3bb1b33a01353cd7f26c9496485e36d954edb | import json
import webapp2
import requests
import requests_toolbelt.adapters.appengine
from . import mongodb
import datetime
from bson.json_util import dumps
class RestHandler(webapp2.RequestHandler):
def dispatch(self):
# time.sleep(1)
super(RestHandler, self).dispatch()
def send_json(self, conten... |
5,363 | 1cccb37a7195b1555513a32ef33b35b0edcd5eb1 | import requests
import datetime
import collections
import csv
import sys
import os
import os.path
History = collections.namedtuple('History', ['open', 'high', 'low', 'close', 'volume', 'adjustment'])
def history(symbol, since, until):
response = requests.get('http://ichart.finance.yahoo.com/table.csv?s=%s&d=%d&e... |
5,364 | 1ee5139cb1613977f1c85619404b3dcc6e996382 | def adder(x, y):
return x + y
adder('one', 'two')
adder([3, 4], [9, 0, 33])
adder(4.3, 3.5) |
5,365 | b35686f7feec2c4a905007f3c105b6fa05b87297 | '''
swea 2806 N-Queen
'''
def nqueen(depth, n, history):
global cnt
if depth == n:
cnt += 1
else:
for i in range(n):
if i not in history:
for index, value in enumerate(history):
if abs(depth - index) == abs(i - value):
b... |
5,366 | 31ed798118f20005b5a26bc1fc0053b7d0a95657 | # Demo - train the decoders & use them to stylize image
from __future__ import print_function
from train import train
from infer import stylize
from utils import list_images
IS_TRAINING = True
# for training
TRAINING_IMGS_PATH = 'MS_COCO'
ENCODER_WEIGHTS_PATH = 'vgg19_normalised.npz'
MODEL_SAVE_PATH = 'models/auto... |
5,367 | f12bdfc054e62dc244a95daad9682790c880f20d | from unittest.case import TestCase
from datetime import datetime
from src.main.domain.Cohort import Cohort
from src.main.domain.Group import Group
from src.main.util.TimeFormatter import TimeFormatter
__author__ = 'continueing'
class CohortTest(TestCase):
def testAnalyzeNewGroups(self):
cohort = Cohort(... |
5,368 | 1d8e48aab59869831defcccdd8902230b0f3daa7 | import random
import pygame
pygame.init()
# 큐브의 크기
cubeSize = 2
# GUI 관련 변수
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 204, 0)
ORANGE = (255, 102, 0)
WHITE = (255, 255, 255)
GREY = (128, 128, 128)
pieceSize = 50
gridSize = pieceSize * cubeSize
screen = pygame.display.se... |
5,369 | dd792c502317288644d4bf5d247999bb08d5f401 | from collections import deque
warp = dict()
u, v = map(int, input().split())
for _ in range(u + v):
s, e = map(int, input().split())
warp[s] = e
q = deque()
q.append(1)
check = [-1] * 101
check[1] = 0
while q:
now = q.popleft()
for k in range(1, 7):
if now + k <= 100 and check[now + k] == -1:
check[now + k] = ... |
5,370 | 82a3fca0261b4bde43f7bf258bb22e5b2ea8c28d | import pickle
import time
start = time.time()
f = open('my_classifier.pickle', 'rb')
cl = pickle.load(f)
f.close()
print(cl.classify("Where to travel in bangalore ?"))
print(cl.classify("Name a golf course in Myrtle beach ."))
print(cl.classify("What body of water does the Danube River flow into ?"))
#print("Accuracy... |
5,371 | 693f2a56578dfb1e4f9c73a0d33c5585070e9f9e | import cv2
import numpy as np
"""
# Create a black image
image = np.zeros((512,512,3), np.uint8)
# Can we make this in black and white?
image_bw = np.zeros((512,512), np.uint8)
cv2.imshow("Black Rectangle (Color)", image)
cv2.imshow("Black Rectangle (B&W)", image_bw)
cv2.waitKey(0)
cv2.destroyAllWindows()
image = ... |
5,372 | 9843f957435b74e63a6fe4827cc17c824f11c7d6 | import time
t0 = time.time()
# ------------------------------
days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def count_days(start_date, end_date, ref_date, target_day):
# ref_date must be exactly 1 year before start_date
month = start_date[0]
day = start_date[1]
year = start_date... |
5,373 | 20671470c087719fa9ea8ffa25be55e9ade67681 | # p.85 (문자 갯수 카운팅)
message = \
'It was a bright cold day in April, and the clocks were striking thirteen.'
print(message, type(message))
msg_dict = dict() #빈 dict() 생성
for msg in message:
print(msg, message.count(msg))
msg_dict[msg] = message.count(msg)
print(msg_dict)
|
5,374 | ba336094d38a47457198919ce60969144a8fdedb | # Generated by Django 3.1.6 on 2021-02-27 23:29
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('RMS', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='inventorytable',
old_name='Restaurant_ID',
... |
5,375 | 1673214215043644e1a878ed7c30b69064f1a022 | import datetime
class assignmentObject:
def __init__(self,name,day):
self.name = name
self.day = day |
5,376 | 88731049227629ed84ff56922d7ac11d4a137984 | from core.models import Atom
from core.models.vector3d import cVector3D
from fractions import Fraction
class SpaceGroup(object):
def __init__(self,
index=None,
name=None,
lattice_system=None,
lattice_centering=None,
inversion=Non... |
5,377 | a777c6d76ef2ae15544a91bcfba0dbeabce0470a | from practice.demo4 import paixu
if __name__ == '__main__':
n=int(input("请输入最大的数字范围:"))
paixu(n) |
5,378 | 0271c45a21047b948946dd76f147692bb16b8bcf | import requests
url='https://item.jd.com/100008348550.html'
try:
r=requests.get(url)
r.raise_for_status()
print(r.encoding)
r.encoding=r.apparent_encoding
print(r.text[:1000])
print(r.apparent_encoding)
except:
print('error')
|
5,379 | 9ba5af7d2b6d4f61bb64a055efb15efa8e08d35c | from selenium import webdriver
from urllib.request import urlopen, Request
from subprocess import check_output
import json
#from flask import Flask
# https://data-live.flightradar24.com/zones/fcgi/feed.js?bounds=-32.27,-34.08,-73.15,-70.29
def get_json_aviones(north, south, west, east):
#driver = webdriver.Chrom... |
5,380 | bcc3d4e9be0de575c97bb3bf11eeb379ab5be458 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 2 22:49:00 2020
@author: Drew
____________________________________________________________________
basic_github_auto_uploader.py - A Basic Automated GitHub Uploader
____________________________________________________________________
1. Requirements:
Version: ... |
5,381 | e4ce10f5db56e4e2e1988da3cee542a4a09785a8 | from . import mongo
col = mongo.cli['Cupidbot']['timer']
async def add_time(chat, time):
return col.insert_one({'chat': chat, 'time': time})
async def get_time(chat):
return col.find_one({'chat': chat})
async def update_time(chat, time):
return col.update_one({'chat': chat}, {'$set': {'chat': chat, 'tim... |
5,382 | 1ce5b97148885950983e39b7e99d0cdfafe4bc16 | from turtle import *
def drawSquare():
for i in range(4):
forward(100)
left(90)
if __name__ == '__main__':
drawSquare()
up()
forward(200)
down()
drawSquare()
mainloop()
|
5,383 | 6267c999d3cec051c33cbcde225ff7acaa6bff74 | import sys
from random import randint
if len(sys.argv) != 2:
print "Usage: generate.py <number of orders>"
sys.exit(1)
n = int(sys.argv[1])
for i in range(0, n):
action = 'A'
orderid = i + 1
side = 'S' if (randint(0,1) == 0) else 'B'
quantity = randint(1,100)
price = randint(100,200)
... |
5,384 | 39ecbf914b0b2b25ce4290eac4198199b90f95e0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
lgr = logging.getLogger(__name__)
lgr.log("hello")
import database
import csv
import codecs
class Stop(object):
"""docstring for Stop"""
def __init__(self, arg):
self.fields = [
'stop_id',
'stop_name',
'stop... |
5,385 | 5dd79f8ebd74099871d4367cafd83359c4f24e26 | #!/usr/bin/python3
import os
import sys
import subprocess
path = sys.argv[1]
name, ext = os.path.splitext(path)
options = ['g++',
'-O3',
'src/' + path,
'-o', f'./bin/{name}',
'-std=c++11',
'-lgmp']
subprocess.call(options)
subprocess.call([f'./bin/{name}'])
|
5,386 | 55d184a9342b40fe027913e46933325bb00e33a6 | from django.contrib import admin
from .models import User, UserProfile, Lead, Agent, Category
admin.site.register(User)
admin.site.register(UserProfile)
admin.site.register(Lead)
admin.site.register(Agent)
admin.site.register(Category)
|
5,387 | 44097da54a0bb03ac14196712111a1489a956689 | #proper clarification for requirement is required
import boto3
s3_resource = boto3.resource('s3')
s3_resource.create_bucket(Bucket=YOUR_BUCKET_NAME, CreateBucketConfiguration={'LocationConstraint': 'eu-west-1'})
s3_resource.Bucket(first_bucket_name).upload_file(Filename=first_file_name, Key=first_file_name)
s3_resource... |
5,388 | cf2c57dbb2c1160321bcd6de98691db48634d5d6 | # Generated by Django 2.2.2 on 2019-07-17 10:02
from django.db import migrations, models
import django.db.models.deletion
import modelcluster.fields
class Migration(migrations.Migration):
dependencies = [
('users', '0003_delete_userprofile'),
]
operations = [
migrations.CreateModel(
... |
5,389 | 0f4fa9f8835ae22032af9faa6c7cb10af3facd79 | def parse_detail_for_one_course(page, course, no_info_course):
print(f'{course["name"]} is processing**: {course["url"]}')
map = {"Locatie": "location",
"Location": "location",
"Startdatum": "effective_start_date",
"Start date": "effective_start_date",
"Duur": "durati... |
5,390 | 0b8cb522c531ac84d363b569a3ea4bfe47f61993 | # ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
"""Module for mimic explainer and explainable surrogate models."""
from .mimic_explainer import MimicExplainer
__all__ = ["MimicExplainer"... |
5,391 | bd1fbdf70bae7d5853bac8fae83343dfa188ca19 | from django import http
from django.utils import simplejson as json
import urllib2
import logging
from google.appengine.api import urlfetch
import cmath
import math
from ams.forthsquare import ForthSquare
from ams.twitter import Twitter
OAUTH_TOKEN='3NX4ATMVS35LKIP25ZOKIVBRGAHFREKGNHTAKQ5NPGMCWOE0'
DEFAULT_RADIUS = ... |
5,392 | e598091fc6c05b1d7f9f35f2ae58494fed53f9af | # Write a Python program to print alphabet pattern 'G'.
result = ''
for row in range(0,7):
for col in range(0,7):
if ((col ==0) and (row !=0 and row !=6) or ((row ==0 or row == 6) and (col>0 and col<6))or ((row ==1 or row == 5 or row == 4)and (col ==6))or ((row ==3)and ((col!=2)and col!=1))):
r... |
5,393 | 7819e41d567daabe64bd6eba62461d9e553566b3 | from socketserver import StreamRequestHandler, TCPServer
from functools import partial
class EchoHandler(StreamRequestHandler):
def __init__(self, *args, ack, **kwargs):
self.ack = ack
super.__init__(*args, **kwargs)
def handle(self):
for line in self.rfile:
self.wfile.wri... |
5,394 | e0b28fdcbc3160bcccbb032949317a91a32eeb1b | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 4 12:47:30 2019
Title: MP4-Medical Image Processing
@author: MP4 Team
"""
# Validate window controller
class ValidateWindowCtr(object):
# Initialization
def __init__(self, fig, im_trans, im_truth, im_segmen, vol_trans, vol_truth, vol_segmen, ax_trans,... |
5,395 | 5b6241907cc97f82d6c6e0a461f4f71a9a567204 | #Program to create and store Employee Salary Records in a file
import os
def appendEmployee(eno,name,basic):
fh=open("Employee.txt","a")
hra=basic*0.10
da=basic*0.73
gross=basic+hra+da
tax=gross*0.3
net=gross-tax
line=str(eno)+","+name+","+str(basic)+","+str(hra)+","+str(da)+","+str(gross)+","+str(tax)+","+str... |
5,396 | 6eec95932ef445ba588f200233495f59c4d77aac | from sklearn.datasets import fetch_mldata
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split
import numpy as np
import os
import tarfile
import pickle
import subprocess
import sys
if sys.version_info.major == 2:
# Backward compatibility with python 2.
from six.... |
5,397 | 8a7904881d936a3cb421ed5550856b600894fcee | #!/bin/python
import sys
import notify2
import subprocess
from time import sleep
def notification(message: str):
"""
Display notification to the desktop
Task:
1. show() -> it will generate a complete new pop
2. update() -> it will update the payload part of same notification pop-up, not is... |
5,398 | b750673829873c136826ae539900451559c042c8 | #Alexis Langlois
'''
Fichier de test pour l'algorithme Adaboost avec arbres de décision (@nbTrees).
'''
import numpy as np
from sklearn.utils import shuffle
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
from adaboost_trees import AdaboostTrees
#Trees
nbTrees = 20
#Tr... |
5,399 | 8ef20a7a93d6affabe88dad4e5d19613fe47dd0f | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import re
import sys
import tarfile
import numpy as np
from six.moves import urllib
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn import datasets
fro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.