index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
992,700
128cb740e0b4da1146c321ee8319f16b7047c2a7
#!/usr/bin/env python3 # ----------------------------------------------------------------------- # amber_test_driver.py # Authors: Hari Raval and Tyler Sorensen # ----------------------------------------------------------------------- import argparse import os import sys sys.path.insert(0,"../src/") import re import cs...
992,701
35017dafeb4835f3cad42c57568cf968a64969f3
# #coding:utf-8 # #Author:Mr Zhi # #4. 将列表['alex', 'eric', 'rain'] 中的每一个元素使用 "_" 连接为一个字符串 # l = ['alex', 'eric', 'rain'] # print('_'.join(l)) # """ # # 20:46:06 # 17-吴 2017/6/13 20:46:06 # 考核形式是怎样的哦。。 # 20:47:06 # 14组导师-刘又源 2017/6/13 20:47:06 # 问答and写点代码 # 14组导师-刘又源 2017/6/13 20:47:12 # 所以你们准备好麦克 # 17-吴 2017/6/13 20:47...
992,702
f1f99ee15e05947f114a6ea561dc53991fe5558d
# -*- coding: utf-8 -*- import mock from mock import call import pytest from h.streamer import nsq from h.streamer import streamer from h.streamer import websocket def test_process_work_queue_sends_nsq_messages_to_nsq_handle_message(session): message = nsq.Message(topic='foo', payload='bar') queue = [messag...
992,703
d51e931c5a937dc3ff0a29dedb2208d46519299a
import torch import torch.functional as F import torch.jit as jit from torch import nn from torch import Tensor class LSTMCell(jit.ScriptModule): def __init__(self, ni, nh): super().__init__() self.ni = ni self.nh = nh self.Wih = nn.Parameter(torch.randn(4 * nh, ni)) ...
992,704
b6e7e19cd459ea0ebf5d4d7e4ce25a50538c5d66
# python创建文件夹和TXT文件,删除TXT文件和删除文件夹 '''需求: 1、先在E盘创建一个TEST文件夹。 2、在TEST文件夹内创建一个TXT文本文件并写入内容“Hello world!” 3、删除TEST文件夹内的TXT文件 4、删除路径TEST文件目录''' import os,stat,time dirPath='E:\\study_dir\\' filename='a.txt' def createfile(): if (os.path.exists(dirPath)): print('目录'+dirPath+'已经存在') else: os.mkdir(dirP...
992,705
33de8edda7487e89b3133e3f9edbbbb4cc4a1bbf
from django.shortcuts import redirect def login_required(view): def _wrapped_view_func(request, *args, **kwargs): if not request.session.get('current_teacher_id'): return redirect('/login') else: return view(request, *args, **kwargs) return _wrapped_view_func
992,706
07d6ce4099e46dec70c6f747f3b5236975a79c8c
#!/usr/bin/python3 """Unittest for review file: class and methods""" import pep8 import unittest from models import review from models.review import Review class TestBaseModelpep8(unittest.TestCase): """Validate pep8""" def test_pep8(self): """test for base file and test_base file pep8""" st...
992,707
9a56d31b469813d6718f85e1abeabeaccca74f03
class Solution: def search_nums(self, nums: List[int], target, start, end)->int: mid: int = (start + end) // 2 res: int = -1 if start<=end: if target == nums[mid]: return mid elif target > nums[mid]: return self.search_nums(nums, targe...
992,708
6a1f4b8d32688708113393be75a71ab6745b61bf
#!/usr/bin/env python3 # # A script for comparing two collection lists from familysearch.org # The lists are JSON files, where the entry 'collections' points to # an array of dictionaries, with keys like: # 'collectionId' : The unique identifier for this collection # 'title' : The Title for this collection (sho...
992,709
b29296399dbc2cdfe43b333b7eb9e07988af529d
import os, urllib.request, time import xml.etree.ElementTree as ET ARXIV_URL = 'http://export.arxiv.org/oai2?verb=ListRecords' METADATA_FORMAT = 'arXivRaw' # possible values: oai_dc, arXiv, arXivRaw OUTPUT_FOLDER = os.path.join('..', '..', 'raw_data', METADATA_FORMAT) if not os.path.exists(OUTPUT_FOLDER): os.mkdir(...
992,710
9a57dec2f3ece67c436eddcf70c20e98286c126a
# Handlers for Transaction Sets import voluptuous from rest_core.resources import Resource from rest_core.resources import RestField from rest_core.resources import DatetimeField from rest_core.resources import ResourceUrlField from rest_core.resources import ResourceIdField from rest_core.exc import DoesNotExistExce...
992,711
173b03c71ed7957ab9bb1cf4e7911da11a8b81c4
from typing import Any from typing import Dict from switchmng.typing import JsonDict class BaseResource(): """ Represents the base for all REST resources. This class only provides the skeleton for other resources and cannot be instantiated. Every implementing class should overwrite `_Attribut...
992,712
938089f96f013a189e294291002138840db27fa9
tab = {'0':'Zero','1' : 'Un','2': 'Deux','3':'Trois','4':'Quatre','5':'Cinq','6':'Six','7':'Sept','8':'Huit','9':'Neuf'} mot = '123' for i in mot: print(tab[i])
992,713
cb3a508f344779c717f3027d297fb1cc4877bebc
__author__ = "rolandh" RESEARCH_AND_SCHOLARSHIP = "http://refeds.org/category/research-and-scholarship" RELEASE = { "": ["eduPersonTargetedID"], RESEARCH_AND_SCHOLARSHIP: [ "eduPersonPrincipalName", "eduPersonScopedAffiliation", "mail", "givenName", "sn", "displ...
992,714
3029e2c99aa1e3f083e5db92872f2e9a96f2c26d
import torch import torch.nn as nn from torchvision.models import resnet18 """ The present python script contains the following classes: * The FeatureExtractor class used to define the feature extractor (Resnet18 without the FC layer),***(Edoardo hai detto che lo facevi quindi te lo lascio) * The MainTask class, used...
992,715
74c22984072bcd99f33abb07fb85fb5842793209
import os from todos.lambda_responses import HttpResponseServerError, HttpOkJSONResponse from todos.todo_model import TodoModel from utils.constants import ENV_VAR_ENVIRONMENT, ENV_VAR_DYNAMODB_TABLE, ENV_VAR_DYNAMODB_REGION def handle(event, context): try: table_name = os.environ[ENV_VAR_DYNAMODB_TABLE]...
992,716
a1ff0ef75372d9e3b6c416a2c3783bd86b51f46e
from rest_framework import serializers from .models import Task, Description class DescriptionSerializer(serializers.ModelSerializer): class Meta: model = Description fields = ('id', 'task', 'text') def update(self, instance, validated_data): validated_data.pop('task') return ...
992,717
76ea3860ecbdce60be7fcaf8d2e495338798e46e
import requests from lxml import etree import json lb = [] zidian = {} def qaqu_syan(url,headers): requ = requests.get(url,headers=headers) print(requ.status_code) with open('雪球信息.txt', 'w', encoding='utf-8') as f: f.write(requ.text) def yiqu_soyan(): with open('雪球信息.txt', 'r', encoding='ut...
992,718
1f2228f105294e2883df52d56c2c6b3bf78b70a6
def solution(cacheSize, cities): res = 0 cache = [] if cacheSize == 0: return len(cities)*5 for c in cities: if c.lower() in cache: res += 1 cache.append(cache.pop(cache.index(c.lower()))) else: if len(cache) >= cacheSize: ca...
992,719
865450330c79d0f002a3922d1fc7d1e406c7d307
import platform import argparse import os import csv import json import re import xml.etree.ElementTree from .ixia_headers import IXIA_RESULT_HEADERS class ParserException: class All(Exception): pass class TestTypeNotFound(All): pass NAS_DRIVE_ADDRESS = '96.37.189.6' def determ...
992,720
189a7f6838532a1eb0fe2c953b2685d56ff3ea37
import cv2 import numpy as np import pytesseract from PIL import Image image = cv2.imread('elect1.jpg') image2 = image.copy() height, width, channel = image.shape gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imwrite('gray.jpg', gray) bulr = cv2.GaussianBlur(gray, (3, 3), 0) cv2.imwrite('bulr.jpg', bulr) canny ...
992,721
bcec6419c00fa11ab4a9ccf81b764b732ff34a8b
# coding: utf8 import logging from datetime import datetime from functools import wraps from ruamel import yaml def read_yaml(yaml_file: str) -> dict: """ Parse any valid yaml/yml file Args: yaml_file: yaml file path Returns: dict """ with open(yaml_file, 'r', encoding="utf8...
992,722
3b9cf102018333cf25b7d9b7aa71db139eead8a6
import unittest from cogent.sip.sipsim import CubicSpline class TestCubic(unittest.TestCase): def testC(self): spline = CubicSpline(0, 1, 2, 0, 5) testpoly = [1, -4, 5, 0] for i in range(len(testpoly)): self.assertAl...
992,723
27feb025c2caf88652aad7d691b1afae5628da47
with open("input.txt") as f: lines = f.readlines() print(sum(map(int, lines)))
992,724
03e86edd54beea36768f499c8f7dd383e2b92f77
# Generated by Django 3.1.7 on 2021-05-22 10:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('work', '0018_auto_20210521_1613'), ] operations = [ migrations.AddField( model_name='sprint', ...
992,725
ae40bd8ce540c1d923189fea02d2ab90be2edf58
print("OK") assert False
992,726
3e93a82807e7b818803ae18da0a15a998ef53cf6
import re def solution(word, pages): word = word.lower() page_info = {} for idx, page in enumerate(pages): text = re.compile("<meta property=\"og:url\" content=\"https://\S*\"", re.I|re.S) text = text.findall(page)[0] pattern = re.compile('https://\S*\w', re.I) cur = pa...
992,727
d12b1332589bf0c9d87da8285a6abd0ca0b35f7b
# Generated by Django 3.0.8 on 2020-10-17 03:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('FirstApp', '0001_initial'), ] operations = [ migrations.AlterField( model_name='movies', name='director', ...
992,728
1a8fa80109df5d4dca5c95e1607c8d6fa63e8780
import numpy as np # Using the scikit-learn library # https://pypi.org/project/scikit-learn/ from sklearn.feature_selection import SelectKBest from sklearn.metrics import accuracy_score from sklearn.model_selection import KFold from sklearn.svm import SVC # Config c_max = 5 c_step = 0.1 gamma_max = 0.1 gamma_step = 0...
992,729
dd37256e65fb1e539901667020f88a0b69263057
import numpy as np from skatingAI.utils.utils import BodyParts class HumanDistanceMap(object): def __init__(self): self.graph = { BodyParts.Head.name: [BodyParts.torso.name], BodyParts.RUpArm.name: [BodyParts.torso.name, BodyParts.RForeArm.name], BodyParts.RForeArm.nam...
992,730
02447512f8b8ef5d6b3b9f6e22346a93fb3f8377
def main(): """ Takes a one line input from STDIN and outputs 'yes' if it is a proper propositional statement, no otherwise. NO WHITESPACE and = '&' or = '|' equivalence = '=' negation = '~' implication = '>' S = sentence P = proposition T/F = Truth Symbols C = Connective ...
992,731
8767eeed406fc4b7beaeff1a5211ad9e7a5ba477
from random import randrange, getrandbits from tkinter import * root = Tk() root.geometry('1050x640') root.resizable(0, 0) root.title("Criptografia RSA - APS segundo semestre v2") topFrame = Frame(root) topFrame.pack(side=TOP) bottomFrame = Frame(root) bottomFrame.pack(side=BOTTOM) leftFrame = Frame(root) leftFram...
992,732
82a58b77fba4fc7c9c102027593160a6e12cbaa2
import rospy import time import numpy as np from ackermann_msgs.msg import AckermannDriveStamped from sensor_msgs.msg import LaserScan from ar_track_alvar_msgs.msg import AlvarMarkers class finalProgram(): def __init__(self): rospy.Subscriber("ackermann_cmd_mux/output", AckermannDriveStamped,self.ackerman...
992,733
a7ad99745700f4b45542629bbe8ed5d4a6cae98f
#!/usr/bin/env python3 import sys import os import configparser myFolder = os.path.split(os.path.realpath(__file__))[0] sys.path.append(os.path.join(myFolder, os.path.pardir)) from windows.window_setting import WindowOption import time __Author__ = 'Zhao Zeming' __Version__ = 1.0 class WindowOptionLogic(WindowOptio...
992,734
68c5092cbbebf128c984951da57f24c9a9625217
#Python problem 9 #This program shows how 2 separate functions calculate square roots, one is using the math library in python and the other is using Newtons square root method #Created by Robert Kiliszewski #04/10/2017 import math x = 100.0 print("Using Math.sqrt() = ", math.sqrt(x)) #Newtons Method for Square Ro...
992,735
22c5698ebeb6b247f841b62ddcfb018d2b5e663a
import sys import os import stat import getopt import random import commands import shutil from sys import path path.append(sys.path[0]+"/lib/") from FuncbioOTU import getAttriValueFromSeqName,fasta2dict def selectRefBySampeSize(minsampleSize,tempDir,copysequence,reference): totalRef=os.path.splitext(copysequence)[...
992,736
76ac1dca6871453bd58cc9aafcb8973b301efc2e
import random import numpy as np from keras.layers import Dense, GRU, Masking, LeakyReLU from keras.models import Sequential from keras.optimizers import Adam from agents.drqn.replay_buffer import ReplayBuffer class LinearSchedule(object): def __init__(self, schedule_timesteps, final_p, initial_p=1.0): ...
992,737
92dbf16d9a63660631454138268b123db34ebdc9
from django.contrib import admin from models import SELIC from models import IGPM from models import IPCA admin.site.register(SELIC) admin.site.register(IGPM) admin.site.register(IPCA)
992,738
0a9635623688fc6533916012d810950b8702adc9
import logging from itertools import izip_longest from time import time, sleep from decorator import decorator # Warning: The simplecache doesn't support the expected lock interface # so make sure to use a lockable cache. # See https://pypi.org/project/redis for an example. from .cache import CACHE, cachekey_static ...
992,739
9dfc25bad470d324c84ada63613dec6e1b4d3b31
if __name__ == '__main__': n,m,k = [int(i) for i in input().strip().split()] nums = [int(i) for i in input().strip().split()] beauty_num = m*k num_sort = sorted(nums,reverse= True)[:beauty_num] num_dict = dict() for i in num_sort: if i not in num_dict: num_dic...
992,740
6f14bb52844a26f7aef17e628a164f8ceaef01c9
from PIL import Image import numpy as np import os from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img sign_labels_map = {'a': 0, 'c': 2, 'b': 1, 'e': 4, 'd': 3, 'f': 5, 'i': 7, 'h': 6, 'k': 8, 'm': 10, 'l': 9, 'o': 12, 'n': 11, 'q': 14, 'p': 13, 'r': 15, 'u': 17, 't': 16, 'w...
992,741
976fdcce1a148cb12c13e0e5b04fb287c879c090
# From SimGeneral/MixingModule/python/mix_2015_25ns_FallMC_matchData_PoissonOOTPU_cfi.py probValue_76X= [ 0.000108643, 0.000388957, 0.000332882, 0.00038397, 0.000549167, 0.00105412, 0.00459007, ...
992,742
4a1d2b2b2fe75d05a80ac3323854382b0068c06e
import smtplib from_addr = 'alexthegreatwilliams@gmail.com' to_addr = 'alexthegreatwilliams@gmail.com' from_name= 'Alex' to_name='Alex' subject= 'Wazzup!' msg='Hows it going bruh' message = """From: {from_name} <{from_addr}> To: {to_name} <{to_addr}> Subject: {subject} {msg} """ message_to_send = message.format(from_...
992,743
a458332d022280ad718edf5bea52f513ab8bfbbc
"""update db Revision ID: 25ac49dfe877 Revises: Create Date: 2019-03-16 15:24:25.564355 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '25ac49dfe877' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generate...
992,744
62027211196641742d1a7290285c4fbf84ab6918
import requests from http.server import BaseHTTPRequestHandler,HTTPServer, SimpleHTTPRequestHandler BASE = "http://localhost:8080/analyze" payload = {"text": "Deep pressure or deep touch pressure is a form of tactile sensory input. This input is most often delivered through firm holding, cuddling, hugging, firm strok...
992,745
a9a2df6f490be00a97ce33e01d0906aaebd3d37a
import sys # https://practice.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s/0 # Given an array A of size N containing 0s, 1s, and 2s; you need to sort the array # in ascending order. # returns the number of zeros, ones and twos (results can be constructed using these counts) # O(n) since we only iterate ...
992,746
73e3f8e147a73a23242d2000e03be6431467d444
from exchanges.hbg.utils import * from market.account import * from market.exchange import * class HBGSpotAccountMgr(AccountManager): def __init__(self, account_secret): super().__init__(account_secret) async def transfer_asset(self, currency, amount, from_field, from_pair, to_field, to_pair): ...
992,747
86f46378392e5c1c2cd027114974a00996a23df8
class Solution: def isPowerOfTwo(self, n: int) -> bool: if n<0: return False count = 0 for _ in range(32): if n&1: count += 1 n = n>>1 return True if count == 1 else False
992,748
29d14dfc7e3ef17096f9305102c6b9e63fd0380f
""" adminrestrict tests """ __author__ = "Robert Romano" __copyright__ = "Copyright 2021 Robert C. Romano" import logging import sys from unittest import skipUnless from django import VERSION as DJANGO_VERSION from django.test import TestCase from django.contrib.auth.models import User from django.core.management im...
992,749
6230ffd9d76da617fb361f7f4d4e577eb07491e6
# area calculation import math print('==============================================================') def calculateCircleArea(): radious = input('Please enter radious of the circle to calculate area: ') if radious.isdigit(): radious = int(radious) area = math.pi*(radious**2) print(f'T...
992,750
4899d8ee22767c94a7795213ce45b9092d532e54
#!/usr/bin/python # -*- coding: utf-8 -*- import sys _ver = sys.version_info py3_or_upper = (_ver[0] > 2) #---------------------------------import--------------------------------------- if py3_or_upper: from urllib.parse import urlencode, quote_plus, parse_qsl, urlsplit, urlparse from urllib.request import Re...
992,751
b506a8554199526897df902a72487f9860afe9e9
import unittest import json from praat import app class TestSoundOps(unittest.TestCase): def setUp(self): app.config['TESTING'] = True app.config['CSRF_ENABLED'] = False self.app = app.test_client() def test_drawSound(self): result = self.app.get("/draw-sound/Part1.mp3/0...
992,752
de32caa9819f9fbe47e3437207b7b3e718b2ef54
from pycoin.encoding import hash160_sec_to_bitcoin_address from services.chroma import ChromaBlockchainState from coloredcoinlib import (BlockchainState, ColorDataBuilderManager, AidedColorDataBuilder, FullScanColorDataBuilder, DataStoreConnection, ...
992,753
6660738359d7c620e158a92fb0130303e1fe83ee
# Key Bindings # 8 - 56 # 6 - 54 # 4 - 52 # 2 - 50 # + - 43 # - - 45 # * - 42 # / - 47 from onvif import ONVIFCamera from msvcrt import getch # Create class for moving PTZ Cam in ContiniousMode using NumPad bindings class my_ptz(): def initialize(self, ip, port, username, password): global...
992,754
b2bbd2f4caf39a915c1a2223b13cf94257e128e0
import sys from PyQt5.QtWidgets import * import win32com.client import ctypes import pandas as pd import os ################################################ # PLUS 공통 OBJECT g_objCodeMgr = win32com.client.Dispatch('CpUtil.CpCodeMgr') g_objCpStatus = win32com.client.Dispatch('CpUtil.CpCybos') g_objCpTrade = win32com....
992,755
aa45d79dc544531f8612aee2eea03ecc97547583
#!/bin/python3 import sys input = sys.stdin.readline def main(): s = list(map(str, input().strip().split()))[0] for i in range(len(s)): c = s[i] if i % 2 == 0: if c == c.upper(): print('No') sys.exit() else: if c == c.lower(): print('No') sys.exit() prin...
992,756
7e3b58c0cfdda4cab1846489e3611e15f15fe60d
from scipy.optimize import leastsq, root import numpy as np from scipy import linalg as lin from scipy import integrate from matplotlib import pylab as plt from scipy.sparse import dia_matrix import timeit class LotkiVolterra: def __init__(self, a, b, c, d, e): self.a, self.b, self.c, self.d, self.e = a, b...
992,757
dcd435844a57fa153cc38afa30af21d5305006d8
from django.db import models class Pizza(models.Model): LARGE = 'L' MEDIUM = 'M' SMALL = 'S' ROZMIARY = ( (LARGE, 'duza'), (MEDIUM, 'srednia'), (SMALL, 'mala'), ) nazwa = models.CharField( verbose_name='pizza', max_length=30, help_text='Nazwa pi...
992,758
4eba3c2c3655eff8ef84f11a42e45cb990534682
# Generated by Django 3.1.7 on 2021-04-20 07:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0004_postrewiews_postid'), ] operations = [ migrations.AlterField( model_name='postrewiews', name='text', ...
992,759
03586dba3010bbb6616be9e757d9151e27736381
import redis import pymongo from pymongo import MongoClient from _include.dbClasses import mongodb as _mongodb r = redis.StrictRedis() #r = redis.StrictRedis(host='localhost', port=6379, db=0, charset="utf-8", decode_responses=True) pubsub = r.pubsub() pubsub.psubscribe("*") print("sdhfhjsgfjgsjdfgsjgdjf") for msg in...
992,760
4ea0265384a9b17dc280472903b3f4fafcb06c29
import feedparser from bs4 import BeautifulSoup import boto3 import os myaccess = os.environ['access'] mysecret = os.environ['secret'] myregion = os.environ['region'] url = "https://towardsdatascience.com/feed" feed = feedparser.parse(url) dynamodb = boto3.resource('dynamodb', aws_access_key_id=myaccess, aws_secret...
992,761
1979d81bbc503a7a01c810ad1a387d95e34d129f
#! /usr/bin/env python3 import numpy as np import os from threading import Lock import logging # ROS import rospy import sensor_msgs.msg import geometry_msgs.msg import tf2_ros import tf import razer_hydra.msg import meshcat import meshcat.geometry as meshcat_geom import meshcat.transformations as meshcat_tf import...
992,762
9243f4a9b5786f21fe52159dc41b07444829d5ca
""" 本函数将字典或嵌套字典中的key从下划线命名法装换为大驼峰命名法, 以便MatCloud MongoDB 的数据查询。 """ import re class Lower2Upper: def __init__(self): self.key_list = [] def get_all_keys(self, query_dict): if isinstance(query_dict, dict): for key in query_dict.keys(): value = query_dict[key] ...
992,763
40619f6dfcc4a191df1acf3f5d4a589d89ba67dd
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Device.info' db.add_column('csp_device', 'info', self.gf('django.db.models.fields.CharFiel...
992,764
404465f6769490f6ad55b73432302ea94b6ba793
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2020-05-10 19:31 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('cricket_series', '0004_player_history_team'), ] o...
992,765
60e918b99da8593b4d951fc992d77d0e1540c23b
##################################### # File Name : PiDrone.py # Author : NayLA # Date : 27/03/2017 ##################################### import sys import argparse , math import time import datetime from TimeStampLib import * from dronekit import connect , Command , LocationGlobal , VehicleMode...
992,766
36831b60b14f26dff41d01e0c98628beabbf0d8f
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for i in tokens: if not stack: stack.append(i) continue if i.lstrip("-").isdigit(): stack.append(i) else: ...
992,767
67aa999e1e3ff0559384d817b6df91bf08ed9a09
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python if len(A) == 0: return '' prefix = '' for max_len in range(max([len(x) for x in A])): prefix_test = A[0][0:max_len+1] for x in A: if...
992,768
a9ffb70688c05929b5c087c0174d5f4f8c991955
#!/usr/miniconda/bin python3.8 # -*- encoding: utf-8 -*- ''' @File : BT_system.py @Time : 2021/10/14 23:18:32 @Author : Jinxing @Version : 1.0 ''' from typing import Dict import pandas as pd import numpy as np import torch as t from torch import nn from TechfinTorchAPI.dataloader.pandas_dataloader impor...
992,769
e1a120e6743b5d9d42853f40b09aae4615e758c2
T = input() for t in range(T): N = input() D = [] M = [] for i in range(N): d,h,m = map(int, raw_input().split()) for j in range(h): D += [d] M += [m+j] if len(D)==1: ans = 0 elif len(D)==2: t1 = M[0]*(360-D[0]) t2 = M[1]*(360-D[1])...
992,770
d390f8572e87cc569d8f3c9387d629c36f317969
import sys input = sys.stdin.readline N = int(input()) graph = [[] for _ in range(N)] for _ in range(N - 1): a, b = map(int, input().split()) a -= 1 b -= 1 graph[a].append(b) graph[b].append(a) c = list(map(int, input().split())) c.sort(reverse = False) tmp = len(graph[0]) start = 0 for index, x ...
992,771
0c31228fbec7cc62d605ef227c5f0f17cc5e6568
import gQuery import numpy as np from MCUtils import * # FIXME: dangerous import from astropy import wcs as pywcs from astropy.io import fits as pyfits import scipy.misc import scipy.ndimage from FileUtils import flat_filename import gnomonic import dbasetools as dbt import galextools as gxt def define_wcs(skypos,skyr...
992,772
e5a6a0d7de48a4f17d4499b0393aa4283ef21c06
# -*- coding: utf-8 -*- """ Created on Thu Dec 10 20:51:08 2020 @author: SivaniDwarampudi """ from random import randint import time """ This is use for create 30 file one by one in each 5 seconds interval. These files will store content dynamically from 'lorem.txt' using below code """ def main()...
992,773
c66c60fc441e3b5c1eff893360ba405f5ce1c348
from django.conf import LazySettings, global_settings from django.contrib.admin.helpers import Fieldline, AdminField, mark_safe from django.contrib.admin.views.main import ChangeList from django.contrib.auth import models as auth_models from django.core.urlresolvers import RegexURLResolver, NoReverseMatch from django.d...
992,774
f4a2046cbd9a099dc93a80667befa2b0591fcd70
# csdaiwei@foxmail.com # naive bayes classifier (multinomial, bernoulli) import pdb import numpy as np from time import time from math import log from math import factorial as ftl class NaiveBayes: def __init__(self, model = 'multinomial'): self.labels = [] #unique class labels self.classprob = {} #prior ...
992,775
a0761b30df9296e0fdaf3971cee55984ee05d9aa
import sys import time from selenium import webdriver from selenium.common.exceptions import TimeoutException, WebDriverException from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver....
992,776
0d7cfa7118fd46e5abca25e7e6ad4f3c454bda1e
from collections import Counter import operator import numpy as np import re from sklearn.model_selection import train_test_split def get_vocabs_chars(data): # Gets the list of words and characters in the dataset all = [word for sent in data for word in sent] chars = list(set(char for word in all for char...
992,777
5e04d1bf6848767b91e68cfd6ce3338611ab168f
from django.contrib import admin from slotting.models import Vendor from slotting.models import MarketDay from slotting.models import Stall from profiles.models import VendorProfile from slotting.models import Assignment class VendorProfileInline(admin.StackedInline): model = VendorProfile class VendorAdmin(admin...
992,778
792e21dffd7a7e0feaaeb8b7c5b98cc44ad517d2
import math import pytest from AutoDiff import autodiff as ad from AutoDiff import * ################# Test functions ##################### def test_negation(): ad1 = ad.AD_eval('-x', "x", 2) assert (ad1.derivative('x'), ad1.val) == (-1, -2) def test_add(): ad1 = ad.AD_eval('x + 2', "x", 2) assert (a...
992,779
e02c2baa425e2bbb01bd8801916860171e285dba
from django.http import HttpResponse def showStatus404(request): return HttpResponse("page is not exist :(", status=404)
992,780
e10da47ab7e7a6cea5dabb84fcbef9df32c365e4
def ticker(filename): dict = {} infile = open(filename, "r+") lst = infile.readlines() for item in lst: item = item[:-2] seperate = item.split(":") dict.update({seperate[0]:seperate[1]}) return dict beursDict = ticker("beurs.txt") print("1. You have a company name: ") print(...
992,781
28898676c1678b18cddbd7395da2235880882696
from settings import * DEBUG = False TEMPLATE_DEBUG = DEBUG EMAIL_PORT = 25 STATIC_URL = '/facegame-static/' MEDIA_URL = '/facegame-media/' # PROJECT_ROOT -> DEPLOY_ROOT # ROOT/releases/release/settings.prod PACKAGE_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', '..', '..', '..')) PROJECT_ROO...
992,782
337f7ca805977f6f367acf5a6ab574d739850a7e
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-01-01 15:24 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('resources', '0001_initial'), ] ...
992,783
a894532594927c44621bd408a0d9bfd612205826
from .base import BaseMessageQueue import redis import json class RedisMessageQueue(BaseMessageQueue): def __init__(self, connUrl, listener=None): super(RedisMessageQueue, self).__init__(connUrl, listener) opts = {} if self.connUrl.hostname: opts['host'] = self.connUrl.hostname ...
992,784
9f0053d2f860e0d25338c70c407f2e1e271e8bc9
import argparse from getpass import getpass from cryptography.exceptions import InvalidSignature from crypto_agile.agility import encipher, decipher, VERSION_CLASSES def encrypt(version, key, input_file, output_file): result = encipher(key=key, plain_text_stream=input_file, ...
992,785
75bab440c2645eeb0c70d18ae689e078744f633f
# -*- coding: utf-8 -*- """ Calculate one and two halo two point correlation functions. """ from __future__ import (absolute_import, division, print_function, unicode_literals) ####import modules######################################################################## import sys import numpy as...
992,786
f0d496b56dc448a0762f10dd3d9ef33cc789cc8d
import subprocess import pandas as pd import re, threading import PySimpleGUI as sg #Create a file to save the output of the pip command of the packages needing upgrade fhandle = open(r'C:\temp\update.txt', 'w') #subprocess.run('pip list --outdated', shell = True, stdout = fhandle) thread = threading.Thread(targ...
992,787
0945f77003c48bbd05995ce24ae27893de618830
import os import sys import random import pickle from pathlib import Path import xgboost as xgb import preprocessing import os os.environ['KMP_DUPLICATE_LIB_OK']='True' from passage_retrieval.supervised_xgboost import predict_passage from answer_extraction.answer_extraction import find_answer SCRIPT_DIR = os.path.d...
992,788
e261cadb108d91bf8956674883536ab0ce7102cf
"""A function to abbreviate strings.""" __author__ = "730407570" def main() -> None: """The entrypoint of the program, when run as a module.""" word: str = input("Write some text with some uppercase letters: ") abbreviation_out: str = abbreviate(word) print(f"The abbreviation is \"{abbreviation_out}\...
992,789
192236ce79f6fc7d24c2fc9d7490ce4db22f1e04
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "David S. Batista" __email__ = "dsbatista@inesc-id.pt" """ In computer science, the maximum subarray problem is the task of finding the contiguous subarray within a one-dimensional array of numbers (containing at least one positive number) which has the large...
992,790
e46365f8b3347a9643473ba678a101fe33181d81
import uuid from src.common.database import Database import src.models.friends.constants as FriendConstant class Friends: def __init__(self, username, friend, _id=None): self.username = username self.friend = friend self._id = uuid.uuid4().hex if _id is None else _id def json(self): ...
992,791
91d115bc7a6eb99390675fe9ce24fb77b616fa10
from django.urls import path from vaccination.admin_views import IndexView, NewCenterView, ApproveView, RejectView, CenterView, WorkerRegister, \ WorkerView, ViewChildren, AddEvent, ViewEvents, AddVaccine, ViewAllocation,TakeChildren, RealloRequest, VaccineView,RequestStatus, \ UpdateReq urlpatterns = [ p...
992,792
f473a85f402fb0dfc36c851d77647ecfac7beb8d
from collections import Counter ''' Revature is building a new API! This API contains functions for validating data, solving problems, and encoding data. The API consists of 10 functions that you must implement. Guidelines: 1) Edit the file to match your first name and last name with the format shown. 2) Provide...
992,793
01a5823a3825baabe3530817bc36d6e52856e378
""" This scripts performs some basic data quality checks to ensure that the transformed data was correctly loaded Airflow will be used for orchestration """ import pandas as pd import numpy as np import os import sys import time import pathlib from datetime import datetime, timedelta import configparser import json ...
992,794
fb685c8d80c4a28a1bf7fed443d3429bb676add5
# Various examples # constants = {"pi": 3.14, "e": 2.71, "root 2": 1.41} # print(constants) # results = {'pass': 0, 'fail': '0'} # print(results) # results['withdrawl'] = 1 # print(results) # results['pass'] = 3 # results['fail'] = results['fail'] + '1' # print(results) # print('Fail = {}'.format(type(results['fail...
992,795
809b513956c33a5a149cc3410c9f8cf8a01859c2
import pandas as pd def checkForeignTables(query, path, database): path += "\\dataDict-" + database + ".csv" df = pd.read_csv(path) for dic in query: relationshipTable = dic['relationshipTable'] relationshipAttribute = dic['relationshipAttribute'] if relationshipTable != 'FALSE': ...
992,796
38a4b1639a9d75b4ff95317e3253e3e4c28c07d4
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2019-Present Datadog, Inc. from __future__ import annotations from typing import Union, TYPE_CHECKING from datado...
992,797
31287674a6974825d45bb32389eb17c9447007ab
""" 항구에 들어오는 배 민석이는 항구가 있는 작은 마을에 산다. 이 항구에는 배가 아주 드물게 지나다닌다. 민석이는 어느날 모든 배들이 항구에 들어온 것을 보았다. 민석이는 이 날을 1일차로 지정하였다. 민석이는 배가 한 척이라도 항구에 들렀던 날을 “즐거운 날"로 이름짓고, 1일차부터 즐거운 날들을 모두 기록하였다. 그러던 중, 한 가지 규칙을 발견했는데, 그 규칙은 각 배들은 항구에 주기적으로 들른다는 것이었다. 예를 들어, 주기가 3인 배는 항구에 1일차, 4일차, 7일차, 10일차 등에 방문하게 된다. 민석이가 1일차부터 기록한 “즐거운 날"...
992,798
15e51f3c4d661ed888e5323ec64f91c661bebc82
import requests import json import sys SerialNumber = sys.argv[1] file = "/vault/data_collection/test_station_config/gh_station_info.json" def read_json_config(file): with open(file) as json_file: config = json.load(json_file) return config stationInfo = read_json_config(file) shopfloorURL = statio...
992,799
38a3c3acaadcf15de99fa619a50d64685e734272
def hello_world(): print("Hello World from Python") def calEMI(): print("EMI is 20K") def homeEMI(): print("Home EMI is 50K") def personalLoanEMI(): print("Personal Loan EMI**")