index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
985,800 | 7662db886454e78090614f95f5931aedf51aa1af | import datetime
from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from .models import ReutersNews, BBCNews, AljazeeraNews, PoliticoNews, EconomistNews, ChristianScienceMonitor
from .models import ChristianScienceMonitor, WikiNews, GuardianNews
from articles.models import Articles
c... |
985,801 | 557550a1df24a439ac1cdb898afaf43d1d5bbdb9 | '''# QUESTION 1
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
spl_char = ['~', ':', "'", '+', '[', '\\', '@', '^', '{', '%', '(', '-', '"', '*', '|', ',', '&', '<', '`', '}', '.', '_', '=', ']', '!', '>', ';', '?', '#', '... |
985,802 | 80d3878f5bfb041c44dcad6803ec5374069619df | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 18 16:32:40 2017
@author: pragun
"""
def printMove(A='A', B='B'):
print('move from ' + str(A) + ' to ' + str(B))
def Towers(n, A='A', B='B', spare='S'):
global move #so funtion can rewrite it
if n == 1:
printMove(A,... |
985,803 | 6a9c20b415cfd4547b17b8aae98e3cf5835ff907 | """
aep_csm_component.py
Created by NWTC Systems Engineering Sub-Task on 2012-08-01.
Copyright (c) NREL. All rights reserved.
"""
import numpy as np
from openmdao.main.api import Component, Assembly, set_as_top, VariableTree
from openmdao.main.datatypes.api import Int, Bool, Float, Array, VarTree
from fusedwind.lib... |
985,804 | abb23135b2c35e2e585e0fdc271dcdfc7573a3cc | import pprint
class ResponseObject(object):
def __init__(self, response):
response = response.json()
for field in response:
value = response[field] if field in response else None
self.__setattr__(field, value)
def json(self):
return pprint.pprint(vars(self))
|
985,805 | 9b14d30eb11a26661637bfe9a24e57a4b17182c1 | # Copyright (C) 2014 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
def main():
import argparse
# Just picks them up from `sys.argv`.
parser = argparse.ArgumentParser(description="Basic parser.")
parser.parse_args()
print("Manual entry point")
|
985,806 | 05dc8cda08dee69094f4c039dbd2a087066faa64 | from django.contrib import admin
from .models import CompanyId, MetricEvent, PermissionBuffer
# Register your models here.
admin.site.register(CompanyId)
admin.site.register(MetricEvent)
admin.site.register(PermissionBuffer)
|
985,807 | 811fa1dc649bae684e7ab1ab556283b155fbb18f | import sys
import tkinter
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtCore import pyqtSlot
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'The Trading Game'
self.left = 10
self.top = 10
... |
985,808 | 9cf1f995c2a8449c47efa4c427291db51dd904a6 | # -*- coding: utf-8 -*-
"""
@author: v. sammartano
"""
#Libraries
import csv
import os
def main():
"""
Thi is the main program
"""
location = os.getcwd()
header = "Date,Time,Voltage,Current,Isolation,Range,SoC,Distance,Fan rpm,Fan Torque,Hyd. Pump rpm,Hyd. Pump Torque,SW Pump rpm,SW Pump Torque,Noz... |
985,809 | 72dac0c99d293e3980365d6adcf36326c97ad8d1 | """
aqui temos um docstring
"""
import cv2
import cv2
captura = cv2.VideoCapture(0)
forc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('gravacao.avi', forc, 20.0, (680, 500))
print(captura.isOpened())
while captura.isOpened():
ret, frame, = captura.read()
if ret:
print(captura.get(... |
985,810 | cc7af0ed26ea42f9faea923fe4008abbfed7a618 | def list_comprehension():
my_list = [4, 10, 3, 1, -4]
# multiple every number in my_list by 2
my_list_2 = []
for num in my_list:
my_list_2.append(num * 2)
print(my_list_2)
my_list_comp = [10 * num for num in my_list]
print(my_list_comp)
import os
# Working with files (read and w... |
985,811 | c11b4da467fb2f18b374368a3e6b1c8b0af00843 | # coding: utf-8
def copy(sources, targets):
return soft_update(sources, targets, 1.0)
def soft_update(sources, targets, tau):
for source, target in zip(sources, targets):
target.assign(tau * source + (1. - tau) * target)
|
985,812 | 3938fa67dd91e58c442a2ef35eb2c58183a61bf2 | ../3.0.0/_downloads/ginput_demo_sgskip.py |
985,813 | 70c40ff121310c8f6a5f06eac647d93b7fd8d1ca | # This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey has `on_delete` set to the desired behavior.
# * Remove `managed = False` lines if ... |
985,814 | 3c58e93f2a757ed60640a879c6c2eb9e6caae875 | """
Move the blocks on tower1 to tower3.
"""
def moveDisks(n, origin, destination, buffer):
if n <= 0:
return
moveDisks(n - 1, origin, buffer, destination)
moveTop(origin, destination)
moveDisks(n - 1, buffer, destination, origin) |
985,815 | cd9db6cce95f49deed7baae3b3516ddcdf8906d9 | "Encap Tests"
|
985,816 | 2eb5caf229ebc61c9b4cf8430631d3451eba8fdf | import librosa
import librosa.display as display
import matplotlib.pyplot as plt
import numpy as np
import math
import tensorflow as tf
from os import walk, mkdir
from glob import glob
from tf_record_single import convert_to
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[valu... |
985,817 | a553a4e0967214e8cd1889b352b72f25381a5f25 | """This submodule handles all interaction with the LALSuite C API.
It provides a class for inputs and a class for outputs and functions for
reading/writing/comparing them. The inputs method has a 'run' method
for calling the C API.
"""
import numpy as np
import glob
import math
import lal_cuda
# Generate mocks for... |
985,818 | 769d337527d0b1c94560c5d2291fcf8130091224 | from graph import Graph
def Prim(G, s):
# Initialize all distances as infinite (represented with -1)
dist = [-1] * len(G)
# Initialize all paths as undefined
parents = [-1] * len(G)
dist[s] = 0
Q = list(range(len(G)))
while len(Q) != 0:
# Getting minimum distance edge in ... |
985,819 | 11cf594d2536d1aae0e4392a259f8ae5f00eb50b | from app import db
from flask_login import UserMixin
from User_login_db import get_db
# Here We arw showing the number of guests can sit in table.
DEFAULT_RESERVATION_LENGTH = 1
MAX_TABLE_CAPACITY = 6
class Guest(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), index=Tr... |
985,820 | 857f6a2f1702e3cdbd397adc9f1a7bd763f58506 | #!/usr/bin/python
#-*- coding: UTF-8 -*-
from django.contrib import admin
from mysite.mmanapp.models import *
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin.widgets import FilteredSelectMultiple
class MManUserAdmin(admin.ModelAdmin):
list_display = ('nic... |
985,821 | 5fdb581702afa45c6912cf35e872158fa46f5129 |
# occiput
# Stefano Pedemonte
# Harvard University, Martinos Center for Biomedical Imaging
# Jan 2014, Boston, MA, USA
__all__ = ['RigidTransformationSSD']
from ilang.Models import Model
from ilang.Graphs import ProbabilisticGraphicalModel
from ilang.Samplers import Sampler
from occiput.Core import Image3D
... |
985,822 | 754ebee0b6fab79b3b6e5c2c42d0a3530f3792c1 | {
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "habitats.py",
"provenance": [],
"collapsed_sections": [],
"authorship_tag": "ABX9TyM9sWj41L/DcsxJJ5ZOD6oO",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name":... |
985,823 | 10d7debadc2534d515da4804c872c3c2aca5a503 | #!/usr/bin/python
## COraTt703.py
#
# Copyright 2010 Joxean Koret <joxeankoret@yahoo.es>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either vers... |
985,824 | 21983675a9ba198a13ebc7e9cae25b33b080745b | lim = 1000
triangles = {}
m = 2
while m**2 < lim:
for n in range(1, m):
k = 1
perimeter = 2 * k * (m ** 2) + 2 * k * m * n
while perimeter <= lim:
if perimeter not in triangles:
triangles[perimeter] = []
triangle = sorted([k*(m**2 - n**2), k*(m**2 + n... |
985,825 | 09b6a48876c58fced1a91b99048197d8bcc7054b | from flask import Flask, render_template, request, url_for
from flask_pymongo import PyMongo
from flask_wtf import FlaskForm
from wtforms import StringField, DecimalField, SelectField, DateField
app = Flask(__name__)
app.config["SECRET_KEY"] = "dnAD67vf68PcDArJ"
app.config[
"MONGO_URI"] = "mongodb+srv://lalbe019:0... |
985,826 | 2f91320a35a457592b207a545f09210fc3a039de | number = float(input())
count = int(input())
print(f'{number:.{count}f}')
|
985,827 | 9470a3fc3afbf2c43b373950690b80566d2c24e3 | # Generated by Django 2.0.2 on 2018-03-06 23:29
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0003_auto_20180306_1014'),
]
operations = [
migrations.AlterModelOptions(
name='emailverifyrecord',
options={'verbo... |
985,828 | aad25f9ff7b62341750fbca7705e2ea60cfbe87e | from cr_scene.models import CrEventScene, CrScene
def get_scene_by_id(scene_id, web=True):
if scene_id is None:
return None
if web:
cr_event = CrEventScene.objects.filter(cr_scene_instance=scene_id).first()
if cr_event is None:
cr_event = CrEventScene.objects.filter(id=scen... |
985,829 | 8b9381d1b8b276704836d71617e8f46e8551b35a | from gladier import GladierBaseTool, generate_flow_definition
def https_download_file(**data):
"""Download a file from HTTPS server"""
import os
import requests
##minimal data inputs payload
server_url = data.get('server_url', '')
file_name = data.get('file_name', '')
file_path = data.get... |
985,830 | ebfe6e213237f6057b437538308905265fdd2ac2 | from urllib.request import urlretrieve
import os
def create_directory(dirname):
if not os.path.exists(dirname):
os.makedirs(dirname)
def downloader(urlarray):
foldername = urlarray[0].split('/')[-1]
urlarray.pop(0)
create_directory(foldername)
download_directory = foldername+"/"
count ... |
985,831 | 8c0a7ee4bc3f8bff16ea3ff3002a27e58de95f3c | # Task:
# In the language of your choice, please write a function that takes in a list of unique people and returns a list of the people sorted.
# People have a name, age, and social security number. Their social security number is guaranteed to be unique.
# The people should be sorted by name (alphabetically) and age... |
985,832 | 29033d7836ecd7661454953980e1870469de9784 | def rev1(str1):
lis = str1.split(" ")
lis.reverse()
print(lis)
a=" "
s2=a.join(lis)
print(s2)
def rev(str):
lis=str.split(" ")
lis2=" "
for i in lis:
lis2+=i[::-1]
lis2+=" "
print(lis2)
str1=input('enter string')
rev1(str1)
rev(str1)
|
985,833 | 8b6374b98acdf3672d25630ea9fd500971ff0903 | # -*- coding: utf-8 -*-
__author__ = 'Jackie'
class Role(object):
def __init__(self, max_health, atk, name=''):
self.__max_health = max_health
self.__cur_health = max_health
self.__atk = atk
self.__is_alive = False
self.__name = name
def get_name(self):
retur... |
985,834 | 4d8ee70476d58656892082ac6207e6572e2096e0 | # Generated by Django 2.2.6 on 2021-04-07 10:34
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('posts', '0018... |
985,835 | 1efd36c4732ea37b1f7b9aa5dc85768752680108 | from datetime import date
from django.db import models
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from wagtail.core.models import Page, Orderable
from wagtail.core.fields import RichTextField
from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel, InlinePanel
from wagtail.im... |
985,836 | 2c39004997bb62931acaea1641a20a4f9829a40d | # No shebang
"""
Collection of utilities for processing CCSM/POP model output.
Created by Ivan Lima on Wed Aug 25 10:01:03 EDT 2004
"""
import numpy as N
import numpy.ma as MA
import os, Nio
import numpy.linalg as LA
POPDIAGPY2 = os.environ['POPDIAG']
if POPDIAGPY2 == 'TRUE':
mappdir = os.environ['ECODATADIR']+... |
985,837 | c430dbecacd8bdfcb381f8d7c7c9c24f6b3da287 | a = int(input('Give me a number: '))
b = int(input('Give me another number'))
if a >> b:
print(str(a) + ' is the bigger number.')
elif a << b:
print(str(b) + ' is the bigger number.')
else:
print('The numbers are equal!')
|
985,838 | 8bf62e56669d9dfbcfb82b73346d93b7ed16da09 | num = int(input("ป้อนตัวเลข : "))
print('"A"\n'*num)
|
985,839 | d84120c58eece9146bebce94c96cae1f3345e334 | # Icons-50 dataset
# https://www.kaggle.com/danhendrycks/icons50?select=Icons-50.npy
'''
Dictionary with keys:
'class', with 10000 elements in {0,1,…,49};
'style', with 10000 elements in {'microsoft', 'apple', …, 'facebook'};
'image' with 10000 3x32x32 images representing the icons;
'rendi... |
985,840 | ea6d479cfafc695ffb685271e88e103d27978bea | def ladderLength( beginWord, endWord, wordList):
"""
Disscussion Method
算法:生成&BFS
思路:
3 4
dot -- dog
1 2 / | | \ 5
hit -- hot | | cog
\ | | /
lot -- log
首先对问题的认识同XiaoXiangMethod,将问题构建为图,但是不... |
985,841 | d912725de2afeeafe8f39c9acfacbed6d7c9b77d | storeNum = int(input())
stores = []
for i in range(storeNum):
line = input().split(" ")
stores.append(list(line))
count = 0
seaLevel = 0
for i in range(storeNum):
min(stores[i])
print(stores) |
985,842 | 96fbccf3e5ab545d8407f2e2c701659aca3bfdfe | import pdb
from time import sleep
import scrapy
from scrapy.selector import Selector
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.option... |
985,843 | 7f84f457aac0825beffdc08305572b97ad4439ea | from enum import Enum
from .header import MgmtHeader, MgmtGroup, MgmtOp, MgmtErr, CmdBase, RequestBase, ResponseBase
import cbor
class MgmtIdOS(Enum):
ECHO = 0
CONS_ECHO_CTRL = 1
TASKSTAT = 2
MPSTAT = 3
DATETIME_STR = 4
RESET = 5
class CmdOS(CmdBase):
... |
985,844 | 46f972b9767a8d27bb1f4e72dd7e0eb30e0dfcc7 | import requests
# 声明一个Session对象
s = requests.Session()
# 修改代理信息
s.proxies = {
"http": "http://127.0.0.1:8888/",
"https": "http://127.0.0.1:8888/"
}
# 设置自定义证书
# # 假设证书在代码目录下的cert文件夹里,文件名为FiddlerRoot.pem
# # 直接使用相对路径
s.verify = r'cert\FiddlerRoot.pem'
# # 如果使用了c_rehash.pl对cert文件夹做了处理,可以修改为如下一行代码
s.verify = r'cer... |
985,845 | e39b7b2e6cef57a82f53ff0bdd57f80379ce2b64 | # import pyowm
# owm = pyowm.OWM('ef2206ff5da67de63306d0b143e20872') # You MUST provide a valid API key
# # Have a pro subscription? Then use:
# # owm = pyowm.OWM(API_key='your-API-key', subscription_type='pro')
# # Search for current weather in London (Great Britain)
# city = input ('Enter a city: ')
# ob... |
985,846 | 04d91891a7a3aa8231b4a9cc3c4e718b0edb350a | import random
def gen_pairs(the_names, number = 10):
for i in range(0, number):
name1 = random.choice(the_names).split()[0]
name2 = random.choice(the_names).split()[0]
while name2 == name1:
name2 = random.choice(the_names).split()[0]
yield f"{name1} teams up with {name2... |
985,847 | 01abcfc47b9645cfc2ae20c7ce2d5753fb48351b | import os
from icrawler.builtin import GoogleImageCrawler
from icrawler.builtin import BingImageCrawler
from icrawler.builtin import BaiduImageCrawler
from icrawler.builtin import FlickrImageCrawler
from icrawler.builtin import GreedyImageCrawler
if __name__ == "__main__":
from optparse import OptionParser
pa... |
985,848 | c773624c5f30f448b9db619182406351307bb444 | from sys import stdin, stdout
from collections import defaultdict
from math import factorial
for line in stdin:
line = line.strip()
cnt = defaultdict(int)
for c in line:
cnt[c] += 1
ans = factorial(len(line))
for k,v in cnt.items():
ans //= factorial(v)
stdout.write(str(ans)+'\n... |
985,849 | b1f49e27d36d97eb4e07a590d5f08d423c04ea0e | from flask import Blueprint, render_template, flash, request, redirect, url_for
from www.extensions import cache
from srmanager.sr import SR
from www.extensions import mongo
main = Blueprint('main', __name__)
@main.route('/')
@cache.cached(timeout=1000)
def home():
srm = SR()
topo = []
for node in srm.ge... |
985,850 | decaf88c28b7ba041c1f845c272dfd2118860d2b | # Module to resize an image
import cv2
image = cv2.imread('lena.jpg')
cv2.imshow('Original', image)
height, width, _ = image.shape
proportion = 100.0 / width
new_size = (100, int(height * proportion))
resized_image = cv2.resize(image, new_size, interpolation=cv2.INTER_AREA)
cv2.imshow('Resized image', resized_image)
cv... |
985,851 | 6d33d07aa654f0785f0b7306fa9ba31354982ae1 | def take_odd(password):
result = ""
for i in range(len(password)):
if i % 2 != 0:
result += password[i]
return result
def cut(index_1, length_1, password):
sub_string = password[index_1:index_1+length_1]
password = password.replace(sub_string, "", 1)
return password
def ... |
985,852 | e72f3caf34f59467b15f244b373405d449c5672c | from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
import json
from api.models import Course, Instructor, LabGroup, Student
from api import permissions
class EnrollTest(APITestCase):
"""
Test ca... |
985,853 | b0ac83ee0af6629295e6a786d5df83f20b8f0056 | def choose_class(name):
if name == 'foo':
class Foo(object):
pass
return Foo # 返回的是类,不是类的实例
else:
class Bar(object):
pass
return Bar
MyClass = choose_class('foo')
print(MyClass) # 函数返回的是类,不是类的实例
# <class '__main__.choose_class.<locals>.Foo'>
print(MyClass(... |
985,854 | 6261cc75790cf6f7e66a44cb4df8e96179aa7145 | # Main file responsible for synchronous stream processing.
from ..matcher.matcher import *
from ..mySDR.mySDR import *
from ..fmDemod.fmDemod import *
from ..myAudio.myAudio import *
from ..db.db import *
import Queue
import threading, time
from ..utils.dbScrape import *
from ..utils.parser import *
import sys, os
from... |
985,855 | 934204d15d2beda66159d54980578b34602bb664 | import fire
from WannabeC import WannabeCCompiler
if __name__ == '__main__':
fire.Fire(WannabeCCompiler)
|
985,856 | 4f4077cca58edf0f9fce60d79b3237b55cb386f9 | from model.debts_model import Debts
class DebtsRepository:
def __init__(self, session):
self._session = session
def insert(self, debts: Debts):
self._session.add(debts)
def get_id(self, id):
return self._session.query(Debts).get(id)
def get_all(self):
return self._s... |
985,857 | 1b2d3f97cfaff96edb2612bf20fc332673fbc7dc | #!/usr/bin/env python3
import logging
import subprocess
logger = logging.getLogger(__name__)
def run_cmd(args_list):
print('Running system command: {0}'.format(' '.join(args_list)))
proc = subprocess.Popen(args_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(output, errors) = proc.communicate()
... |
985,858 | e89982fedc8a2b8f90f4656767c3c51d2b3c9f2d | # Generated by Django 3.2.3 on 2021-06-04 02:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('apps', '0004_auto_20210523_1107'),
]
operations = [
migrations.RenameField(
model_name='profile',
old_name='full_nam... |
985,859 | 8a64a0b955f3c04e4c3031e184764cf6c2ca03f2 | # -*- coding:utf-8*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
import os.path
import time
time1=time.time()
def MergeTxt(filepath,outfile):
k = open(filepath+outfile, 'a+')
for parent, dirnames, filenames in os.walk(filepath):
for filepath in filenames:
txtPath = os.... |
985,860 | 0ed2cbb9f9d59bd2610bc6f9c8e566a8d2268b8c | # 치환문 예
a = 1
b = a+1
print(a, b, sep=' , ')
# 한줄에 동시에 대입하고싶음
# 세미클론으로 치환문을 구분할 수 있다,
e = 3.5 ; f= 5.3
print(e, f)
# 여러 개를 한번에 치환하기
e, f = 3.5, 5.3
print(e,f) # packing unpacking이 일어나는 것
# 같은 값을 여러 변수에 대입
x = y = z = 10
# c 스타일은 지원 x
# x = (y=10) 같은
print(x,y,z)
# 동적 타이핑 : 변수에 새로운 값이 할당되면 값을 버리고 새로운 값으로 치환된다
... |
985,861 | 7ed75507a58d17fdf0f331066e5c55e40ac1f727 | import pytz
from django.utils import timezone
from django.contrib.sessions.middleware import SessionMiddleware
from django.utils.deprecation import MiddlewareMixin
class SessionCustomMiddleware(SessionMiddleware):
def process_request(self, request):
super().process_request(request)
if not request.... |
985,862 | e7b078d153b1a54a42ac95bacab1d22ab57281b1 | from keras.engine import Layer, InputSpec
from keras import initializations, regularizers
from keras import backend as K
import tensorflow as tf
#!!!!Change axis to adapt for different than dim_ordering=theano and backend=tf!!!!
class Bias(Layer):
'''
Simple bias layer
'''
def __init__(self, axis=1, mo... |
985,863 | d48411d0d54ac477b0c104bd69057a3806ae69ad | from django.db import models
class Feature (models.Model):
creator = models.ForeignKey('account.User')
title = models.CharField(max_length=120)
desc = models.TextField('Description')
approved = models.BooleanField(default=False)
closed = models.BooleanField(default=False)
votes = models.IntegerFie... |
985,864 | f93fa0d6d3d9e29540f3cdfeda13712adb1d4b09 | # algorithm quicksort(A, lo, hi):
# if lo < hi then
# p ← pivot(A, lo, hi)
# left, right ← three-way-partition(A, p, lo, hi)
# quicksort(A, lo, left - 1)
# quicksort(A, right, hi)
# procedure three-way-partition(A, pivot, lo, hi):
# l ← lo
# r ← lo
# u ← hi
# while... |
985,865 | ccbbcc5961ff1470f8dadfc206d0037014bf60c2 | # Taxis agent construct a probability distribution for the best spot on the board
# each spot on the board has some values associated with it
import random
import math
import sys
sys.path.insert(0, './../utils')
import configurations as cf
import utilities as ut
from scipy import stats
import matplotlib.pyplot as pl... |
985,866 | b579c007bc1b845e64442fc342068f8f954da35f | #!/usr/bin/env python
from __future__ import division # make sure division yields floating
import sys, re
import argparse
import numpy as np
def main(args):
is_include = {}
is_test = {}
for ii, line in enumerate(args.m):
fields = line.strip().split('\t')
if (ii == 0):
groups ... |
985,867 | 45d4625794f7ba3e364a8963a2a945101151c94e | import datetime
import pandas as pd
import pandas_datareader as web
import plotille
# select start date for correlation window as well as list of tickers
start = datetime.datetime(2020, 1, 1)
end = datetime.datetime(2020, 3, 4)
symbols_list = ['SPY', 'AAPL']
# array to store prices
symbols = []
# pull price using... |
985,868 | 53124f592c2cf87e4e27d78793648b840a19372f | from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
# Create your views here.
def login_page(request):
if request.method == 'POST':
user = authenticate(username=request.POST['uname'], password=request.POST['passwd'])
if user is not None and use... |
985,869 | a5f4a26d347bbfea4c8a31e974f451c6b891f9c9 | import math
import numpy as np
from numpy.linalg import norm, lstsq, inv, cholesky
from scipy.linalg import toeplitz
from scipy.optimize import least_squares
import matplotlib.pyplot as plt
from sklearn.base import BaseEstimator
def convert_deriv_to_mag(J,dpred):
"""
Convert jacobian matrix of complex derivat... |
985,870 | c6d33a0c7c54d00f9380ecdbc9cf26fb215609ce | # Train a statistical tagger.
# Mark Amiguous data
# Make a decision tree of each amabigious class
from features import data_or_empty, set_encoder, encode_features,extract_feature
import analytics,corpus
from corpus import load_corpus
import numpy as np
import sys
try:
TEST = int(sys.argv[1])
except ValueError:... |
985,871 | 78955a1b2751e611aceecdbfa1eff7c77e1b4c8e | from IPython.display import clear_output, Image, display, HTML
import tensorflow as tf
import subprocess
import re
import os
import logging
import ngrok
import urllib.parse
def strip_graph_consts(graph_def, max_const_size=32):
"""
Strip large constant values from graph_def.
"""
strip_def = tf.GraphDef(... |
985,872 | 60d8c90c34bb8a4b31d31df22118ea0be0e43f92 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 10 09:45:07 2018
@author: wfsha
"""
import pandas as pd
import numpy as np
spotlist = pd.read_csv('C:/Users/wfsha/Desktop/list.csv',names=['id','spot','coordi'])
spotlist['co'] = np.array
for li in range(len(spotlist['id'])):
spotlist['co'][li] = []
for i in s... |
985,873 | 1b2bc8b1d204cd8d81278fa248abb56f89df63bb | from django.shortcuts import render, HttpResponse
from .forms import FileUploadFormForm, FileUploadFormModelForm
def index(request):
if request.method == 'POST':
#
# This Is The Basic Form Method
#
# form = FileUploadFormForm(request.POST, request.FILES)
form = FileUploadForm... |
985,874 | 1fbee19032fecb8191f0eb99993a7d32a95d61de | from flask import Flask, render_template, request, redirect, session
app = Flask(__name__)
app.secret_key = 'keep it secret, keep it safe, hush hush!'
@app.route('/')
def counter():
if 'counter' in session:
session['counter'] += 1
else:
session['counter'] = 0
return render_template("index.h... |
985,875 | 1395390cf133c8d3f5089c024567a6f86917608c | from __future__ import print_function
from keras.callbacks import LambdaCallback, ModelCheckpoint,ReduceLROnPlateau
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.layers import Dropout
from keras.layers import LSTM
from keras.layers import RNN
from keras.utils.data_utils impor... |
985,876 | 122391fb521322df1d6d61329cbaf66dff2c3cd1 | import csv
from unittest import TestCase
from DB.schema_definition import Author, Post, Claim_Tweet_Connection, DB, Claim
from commons.commons import convert_str_to_unicode_datetime
from preprocessing_tools.fake_news_word_classifier.fake_news_word_classifier import FakeNewsClassifier
class TestFakeNewsClassifier(Tes... |
985,877 | 40d477834a4e942bb64bffb2a50fdfbf0731cb8d | class Patent(object):
patent_id = ""
patent_name = ""
medicine_components = None
patent_form = None
patent_major = None
patent_functions = None
def __init__(self):
pass |
985,878 | 4b30a29c67cbdf7b76f10f040b88aeff8f713317 | from .BeamOrientation import BeamOrientation
class BeamOrientationArray(list[BeamOrientation]):
def findAt(self):
pass
|
985,879 | cce0686386eac7ba0dcbbde5098e88a6bca555bb | import sys
import os
import re
backlog = []
def main(argv):
source = r'f:\Family Fotky'
print('Source path: {}'.format(source))
extension = re.compile(r'^.*\..+_\d{3}$')
for root, dirs, files in os.walk(source):
duplicates = [duplicate for duplicate in files if extension.match... |
985,880 | 8624b1722587a070d614add986464a915fc12676 | import pytest
import aiohttp
from aiohttp import web
async def test_async_with_session(loop):
async with aiohttp.ClientSession(loop=loop) as session:
pass
assert session.closed
async def test_close_resp_on_error_async_with_session(loop, test_server):
async def handler(request):
return w... |
985,881 | 907a7df5d8652c164acf5c3d2d5d3e4b090f9876 | from benchmark_reader import Benchmark
from benchmark_reader import select_files
# where to find the corpus
path_to_corpus = '../benchmark/original/test'
# initialise Benchmark object
b = Benchmark()
# collect xml files
files = select_files(path_to_corpus)
# load files to Benchmark
b.fill_benchmark(files)
entitie... |
985,882 | 348f8bfcec9dc4e5e32091cd4efd03a935655533 | def print_timesTable() :
for i in range(2,10):
print("===",i,"===")
for j in range(1,10):
print(i,"x",j,"=",i*j)
print_timesTable()
#https://wikidocs.net/24
num = [1,2,3,4]
num.append(5)
print(num)
num.insert(0,0)
print(num)
num.extend([6,7])
print(num)
color = ['red','blue','ye... |
985,883 | f2360f39c0cb2df54d51629ab0eeee067dd86cd8 | import json
import geojson
from django.test import TestCase
from django.urls import reverse
def randomFeature():
return {
"type":"Feature",
"geometry": geojson.utils.generate_random("Polygon"),
"properties":{}
}
def returnData(inner):
def wrapper(*args,**kwargs):
r = inne... |
985,884 | a41632de1f510d0577eeae1d3b3c8482b00d6914 | import csv
from datetime import datetime
import io
import logging
import os
import re
import traceback
from utils.event_source_map import event_source_map
class CsvFormatter(logging.Formatter):
def __init__(self):
self.output = io.StringIO()
self.writer = csv.writer(self.output, quoting=csv.QUOTE... |
985,885 | efc61574c543e3aafb0b1ea30714204602c3561f | import pygame
from defs import *
import numpy as np
import random
class Plataform():
def __init__(self, gameDisplay, brain):
self.gameDisplay = gameDisplay;
self.x = PLATAFORM_POSITION[0]
self.y = PLATAFORM_POSITION[1]
self.plat_color = self.random_color()
self.rect = self.draw()
self.points = 0
self.br... |
985,886 | 9fc23e62ee714c089fea23707f42141fff6e8e67 | import pyautogui
pyautogui.hotkey('command', 'tab')
pyautogui.press('z') |
985,887 | 2bd763ab20585d60e215fd00dad0fbb2617ba619 | import logging
import re
import certifi
from ssl import create_default_context
from elasticsearch import Elasticsearch
from copy import copy
from sokannonser import settings
from sokannonser.repository.ontology import Ontology
log = logging.getLogger(__name__)
OP_NONE = ''
OP_PLUS = '+'
OP_MINUS = '-'
class TextToC... |
985,888 | a7bdcfe35ee2782ea12e033812e242f8b22e38dc | import re
from util import *
import wl_data as wl
import matcher
help_command_color = '1;37'
def command_format(cmd):
if check_gdb():
return '(gdb) ' + color(help_command_color, 'wl' + cmd)
else:
return '$ ' + color(help_command_color, cmd)
class Command:
def __init__(self, name, arg, fun... |
985,889 | da47948c1c1a03fc4d03b0d07c4da62381fd56a2 | import pandas as pd
sheets = []
with pd.ExcelFile("/home/ccalleri/Documents/Charlotte/AutomtisationInfosNutritionelles/données nutritionnelles.ods") as xls:
print(xls.sheet_names)
sheets = xls.sheet_names
dfs = [pd.read_excel(xls, sheet_name, engine="odf") for sheet_name in xls.sheet_names]
donnees_nu... |
985,890 | fd3a23714a0e3899e21fb275ffa8099277d73615 | class Solution(object):
def slowestKey(self, releaseTimes, keysPressed):
"""
:type releaseTimes: List[int]
:type keysPressed: str
:rtype: str
"""
prev = 0
output = (0, '')
for key,time in zip(keysPressed, releaseTimes):
output = max(output,... |
985,891 | c5ddd9c7dabd38ed20f047443e24ccbc207389ca | # -*- coding: utf-8 -*-
'''
Created on Nov 7, 2010
@author: morten
'''
import unittest
from Output.TableOutput.TableOutput import TableOutput
#from Datatypes.ActivityData import ActivityData
from testpackage.Utilities.TestdataSupport.TableOutput import * #@UnusedWildImport
# test data
class Test(unittest.TestCase):... |
985,892 | 8c8a2c7707f8a15794ed8b521a1b4857d9a07f2a | class PeakFinder:
def __init__(self, threshold):
self.threshold = threshold
self.last = 0
self.name = f'nrm_peak{threshold}'
def is_peak(self, value):
difference = value - self.last
previous = self.last
self.last = value
if difference > (self.threshold ... |
985,893 | 9e6a4908fcff92a103985a83abc057aa7a8af3be | """
You have to create different func,ons for Sam’s college of cartoon. Please find the func,ons list
below -
• Give me a random cartoon character: - Func?on 1
• This func,on should take N arguments, where N is not fixed and ranges from 0 to
many. This func,on should return a random character from the N... |
985,894 | 0a99291e6e994b39f605ca4a34fb686638eea9ae | import sys
from konlpy.tag import Komoran
komoran = Komoran()
sentences = sys.argv[1]
#sentences = '사과, 감자, 이것은 테스트입니다'
#s = sentences.encode('utf8')
morphs = komoran.pos(sentences) #pos: Every mophs
#morphs = komoran.nouns(sentences) # nouns: N
morphs.sort()
i=0
k=0
nat = [[0]*2 for _ in range(... |
985,895 | 00f92d04ad58a2fa45ff40b00e2a71ead2a26048 | from pyalgotrade import dataseries
from pyalgotrade import technical
# An EventWindow is responsible for making calculations using a window of values.
class Accumulator(technical.EventWindow):
def getValue(self):
ret = None
if self.windowFull():
ret = self.getValues().sum()
ret... |
985,896 | 701838cf9766eeb7bae2ec249037e3da65d8c587 | from distance_functions.handle_numbers import find_numbers
import roman
import re
def get_physical_information(physical_description: str):
pages, volume_nr, is_multiple_volume = [], 1, 0
description_splitted = physical_description.split('. -')
if len(description_splitted) > 1:
multi_volume_indicat... |
985,897 | 866981f75ceb97525cf33b198cb66a7e3e99b454 | from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from .models import Client,Manager
from information.models import *
from django.contrib import auth
# Create your views here.
# def re(response):
# return response
def index(request):
if request.method == "GET":
... |
985,898 | 086b1f51f20921d0d2461f74a07983294e66fcde | #Embedded file name: ui/cocoa/selective_sync.py
from __future__ import absolute_import
import os
import time
from objc import YES, NO, ivar
from Foundation import NSFileTypeForHFSTypeCode, NSMakeRect, NSMakeSize, NSMaxX, NSMaxY, NSObject, NSPoint, NSRect, NSSize, NSZeroRect
from AppKit import NSApp, NSBackingStoreBuffe... |
985,899 | 521a6c04e5dd9e1830321bed2e6a065d176d5783 | import matplotlib.pyplot as plt
import math
import os
import re
import sys
dir=os.getcwd()
dir_list=dir.split("/")
loc=[i for i in range(0, len(dir_list)) if dir_list[i]=="General_electrochemistry"]
source_list=dir_list[:loc[0]+1] + ["src"]
source_loc=("/").join(source_list)
sys.path.append(source_loc)
print(sys.path)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.