index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
16,200 | e3cd7ef1d84c54b8373f0a4bdcbdee02d445cdb5 | import main
#alreadyImported = []
def compilefile(file, n=None):
main.main(file, n=n) |
16,201 | 0ea86680d5d4a980769e3b020326ecdc4053813f | import scrapy
class QuotesSpider(scrapy.Spider):
name = "bok"
def start_requests(self):
# base url for BOK minutes
urls = [
'https://www.bok.or.kr/portal/bbs/B0000245/list.do?menuNo=200761&sdate=2005-05-01&edate=2017-12-31',
]
for url in urls:
yield scr... |
16,202 | 1af2843d8090214d0aa24f184fd7204a942a1e8e | from collections import deque
"""
题目一: 滑动窗口的最大值
"""
def max_in_windows(array, win_size):
if not isinstance(array, list) or len(array) == 0 or win_size < 1 or win_size > len(array):
return
max_of_window = []
index_deque = deque()
for i in range(win_size):
while len(index_deque) != 0... |
16,203 | d740602a5a64a703b8c7a90cd912704e311d08af | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 2 15:31:00 2021
@author: 洪睿
"""
import numpy as np
import gym
#from utils import plotLearning
import tensorflow as tf
tf.compat.v1.enable_eager_execution()
#tf.compat.v1.disable_eager_execution()
num_simulation = 10000
env = TradingEnv(num_sim = num_... |
16,204 | ef81c6a964bd51fbb6ec1eac2747c16ac612eaaa | import torch
import torch.nn as nn
from .Attention import Attention
from models.base_model import BaseModel
from .Encoders.MHA import MHA_User_Encoder,MHA_Encoder
class NRMS(BaseModel):
def __init__(self, hparams, vocab, encoder):
super().__init__(hparams)
self.name = 'nrms' + encoder.name
... |
16,205 | de172374728efdb31b3fc4c18f23aff76e905d64 | from datetime import datetime
from dateutil import relativedelta
import sys
now = datetime.now()
try:
iyears = int(input("Please write the year in which you were born: "))
imonths = int(input("Please write the month in which you were born: "))
idays = int(input("Please write the day in which you were born: ... |
16,206 | a3ebe00d848512030a29474536e6c462a0415902 | # Given a filename and a string, find the location of the file
# and where in the file the string is located
from os import walk, path
f = input("File: ") # Ask for file to find; EXACT
s = input("String: ") # Ask for string to find in file; EXACT
for root, dirs, files in w... |
16,207 | aa7a38b830756a312203b3d22f6f93b6216e5bac | from django.db import models
class CovidObservations(models.Model):
sno = models.IntegerField(primary_key=True, )
observation_date = models.DateField()
province_state = models.CharField(max_length=255)
country_region = models.CharField(max_length=255)
last_update = models.DateTimeField()
confirmed = models.Integ... |
16,208 | c6c817499dc30352110fb917e9cd20b3f63637c3 | import datetime
from django.db import transaction
from rest_framework import generics, status
from rest_framework.exceptions import NotFound
from rest_framework.response import Response
from contacts.models import Contact
from contacts.serializers import ContactSerializer, ContactNestedSerializer
class SearchContact... |
16,209 | ceddedc4dc22d0ee66258b284c3a0b9a709a5847 | from ai.nn.layer import *
from ai.nn.helpers import *
from ai.nn.network import *
from ai.dqn import DQN
from ai.drqn import DRQN
def drqn_model1(session):
batch_size = 16
time_steps = 16
qnn = NeuralNetwork([
Reshape(lambda (A,B,C,D,E): (batch_size*time_steps,C,D,E)),
Merge([
... |
16,210 | 2162636cce37ef15d2cdf86c4c80fa1d2e81a105 | from forte_fives import card
from forte_fives import deck
import unittest
class Deck_init(unittest.TestCase):
def setUp(self):
self.mydeck = deck.Deck()
def tearDown(self):
self.mydeck = None
def test_correct_size(self):
self.assertTrue(len(self.mydeck.cards) == 52)
def t... |
16,211 | 42cdc714068a884a117183056fe36a099dfdb7d1 | def sol(datas):
cnt = 0
result = []
for data in datas:
if data != 0:
result.append(data)
else:
cnt +=1
for i in range(cnt):
result.append(0)
print(result)
if __name__ == "__main__":
sol([6, 0, 8, 2, 3, 0, 4, 0, 1])
|
16,212 | 859057efd3966e6e53db7cd18f65cee796009624 | import os, json, unittest, time, shutil, sys
sys.path.extend(['.','..','py'])
import h2o, h2o_cmd, h2o_hosts, h2o_util, h2o_log
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
localhost = h2o.decide_if_localhost()
... |
16,213 | 184928431ec5ea2c26f2a1b15a02240ef5d9cc96 | # coding: utf-8
'''
File: tracker.py
Project: AlphaPose
File Created: Thursday, 1st March 2018 6:12:23 pm
Author: Yuliang Xiu (yuliangxiu@sjtu.edu.cn)
-----
Last Modified: Monday, 1st October 2018 12:53:12 pm
Modified By: Yuliang Xiu (yuliangxiu@sjtu.edu.cn>)
-----
Copyright 2018 - 2018 Shanghai Jiao Tong University, ... |
16,214 | ce6fbc081120f35ed8f7d122bfbf1ef8a9e0d78f | from rest_framework import serializers
from .models import Comment
from django.contrib.auth.models import User
class OwnerSerializer(serializers.RelatedField):
def to_representation(self, value):
return {'id':value.id, 'username': value.username}
class CommentSerializer(serializers.HyperlinkedModelSerializer):
o... |
16,215 | cebf6d0793ef564fd8647f8917b6cc278e0ff2bb | import multiprocessing
import os
import sys
import time
import webbrowser
from flask import Flask
client_id = 'c895de4e2dde4f32886ec383d6f39bd8'
redirect_uri = 'http://localhost:8642/'
config = {'client_id': client_id,
'redirect_uri': redirect_uri}
app = Flask(__name__)
@app.route('/', methods=['GET']... |
16,216 | 83e486e38d2e3808685f1c245671bf3603c45254 | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
rows = [21, 7, 9, 12, 2, 10, 3, 27]
cols = [1, 4, 17, 20, 22, 16, 8, 25]
heart = [
[1, 0, 0, 1, 1, 0, 0, 1],
[0, 1, 1, 0, 0, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 0],
[1, 0, 1, 1, 1, 1, 0, 1],
[1, 1, 0, 1, 1, 0, 1,... |
16,217 | c2baa8dc5f47ce63a143b65cf864399a8db890b3 | from django.shortcuts import render
from django.http import HttpResponse,JsonResponse,FileResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from colcon.models import Profile,UserDetail,ProfileSerializer,Post,Channel,Pos... |
16,218 | 3f88a8b0692d939e2c7a715b5a65d53593dd9c83 |
class Solution:
def numDecodings(self, s: str) -> int:
"""
https://leetcode.com/problems/decode-ways-ii/
A message containing letters from A-Z is being encoded to numbers using the following mapping way:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Beyond that,... |
16,219 | c28cba14dc1355f203b609bcae7a4bd291fdedad | execfile('')
from boto.s3.connection import S3Connection
s3 = S3Connection()
bucket = s3.get_bucket('sgcs15spproj6tokyo')
from boto.dynamodb2.table import Table
ngram = Table('prjsixresult') # using table name
for s3object in bucket.list():
if 'output' in s3object.key a... |
16,220 | 9240bd828ae23621d704952283e4f35148e21815 | from django.conf.urls.defaults import *
from django.views.generic import ListView, DetailView
from stet.models import Article
urlpatterns = patterns('',
(r'^$', ListView.as_view(
model=Article,
)),
(r'^(?P<pk>\d+)$', DetailView.as_view(
model=Article,
)),
(r'^comments/', include('d... |
16,221 | dd0c2770779507917271b3e47643dd8a077d5073 | def f(a):
s = ""
i = 0
while(i < len(a) - 1):
s = s + a[i + 1]
i = i + 1
return s
def g(a, b):
if(b == 0):
return a
return f(a) + a[0]
s = "0123456789"
i = 0
while(i < 7):
j = 0
while(j < 2):
s = g(s, 1)
j = j + 1
s = g(s, 9)
i = ... |
16,222 | 82b78b238c59e785018d03db5b02ee511c4b9e40 | from quiz.models import Quiz
from rest_framework import serializers
from .create_quiz import QuestionSerializer
class QuizRetrieveSerializer(serializers.ModelSerializer):
questions = QuestionSerializer(many=True, source='question_set')
class Meta:
model = Quiz
fields = ('id', 'questions')
|
16,223 | 6eb27d2be931c57bf459d26e1d01cb94db065892 | # import the necessary packages
from __future__ import print_function
import argparse
import app_logic as logic
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--display", type=int, default=-1,
help="Whether or not frames should be displayed")
args = vars(ap.parse_args())
if args["display"] > 0:
logic.display... |
16,224 | 4a9ea518153ff2c678c62da0e60893ec2df0b723 | #!/usr/bin/python3
from flask import Flask
from datetime import datetime, timedelta
from threading import Thread
from os import system
from random import randint
last_load = datetime.now()
def grim_reaper():
'''
If site not loaded for 10s reboot host
reboot can be prevented by calling life_line()
'''
... |
16,225 | 81d0448232a293483e6a2966b8a84e05e0be8db0 | import discord
from discord.ext import commands
import json
class Ping:
conf = {}
def __init__(self, bot, config):
self.bot = bot
self.config = config
global conf
conf = config
@commands.command(pass_context=True)
@commands.guild_only()
@commands.cooldown(1, 30,... |
16,226 | 8eea6b90d7f523ab13fb6b3e64049caba87205e9 | from django.contrib import admin
from cinema.models import Hall
from cinema.models import Movie
from cinema.models import Session
from cinema.models import TicketStatus
from cinema.models import Ticket
admin.site.register(Hall)
admin.site.register(Movie)
admin.site.register(Session)
admin.site.register(Tic... |
16,227 | ada2d6893864df2465083eb31616f240061a7590 | # -*- coding: utf-8 -*-
from datetime import datetime
from sqlalchemy import Column, Integer, String, ForeignKey, Table
from sqlalchemy import Boolean, DateTime, Date
from sqlalchemy import Table, UniqueConstraint
from sqlalchemy.orm import relation
from sqlalchemy.schema import MetaData
from sqlalchemy.ext.declarativ... |
16,228 | 740dd474cf8405d11f9f95f608c2f329d0c04bd7 | import os
import urllib
import re
import random
#import md5
import hashlib
from amilib.useful import Singleton
from amilib.amiweb.amiweb import session
from amilib.amiweb.amidb import IntegrityError
from amilib.template import render
from amilib.amiweb.amigration import AMigrationControl, Not_Created
from amilib impor... |
16,229 | 91aea36cb3ae003842d923d03cb5c68149c74474 | # Las Diccionary son con llaves y separados los valores por comas
# Permite modificar
# Permite ordenado
# No permite duplicados
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
print(thisdict["brand"]) |
16,230 | e890e13019c4038d8777a8bc8a876fd07ca8ec0d | import sys
# 숫자의 합
def sum_digits(number):
digit = [int(x) for x in str(number)]
result = sum(digit)
return result
# main
if __name__ == '__main__':
N = int(sys.stdin.readline().rstrip()) # 숫자의 개수
number = int(sys.stdin.readline().rstrip())
answer = sum_digits(number)
print(answer) |
16,231 | 01f6588a8ba17abb5346d5738cae3ef960106c19 | import mysql.connector
config = {
'user': 'root',
'password': 'eabsen.kalselprov.go.id',
'host': 'localhost',
'database': 'data_finger',
'raise_on_warnings': True,
}
#TEST ACCOUNT
# config = {
# 'user': 'root',
# 'password': '123456',
# 'host': 'localhost',
# 'database': 'data_finger',
# '... |
16,232 | 44170d18478edcff93a806f619e8967c1939b2d8 | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
16,233 | 28d2af41cce5704fd7a838ad93a927903f46a745 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import common
from bs4 import BeautifulSoup
import mysqlop
class AnHui():
_url = 'www.ccgp-anhui.gov.cn'
_baseurl = 'http://www.ccgp-anhui.gov.cn/'
_posturl = '/mhxt/MhxtSearchBulletinController.zc?method=bulletinChannelRightDown'
_title = u'安徽省政府采购'
... |
16,234 | 76483ced2e9552445261a04ae68b50741ef069a6 | from __future__ import print_function
import ROOT,uproot
xml_files=[
'MC_QCD_Pt_1000to1400_2017v2_46.xml',
'MC_QCD_Pt_1000to1400_2017v2_48.xml',
'MC_QCD_Pt_1000to1400_2017v2_51.xml',
'MC_QCD_Pt_1000to1400_2017v2_52.xml',
'MC_QCD_Pt_1000to1400_2017v2_54.xml',
'MC_QCD_Pt_1000to1400_2017v2_5... |
16,235 | 53ec0da22e1b9577a6751337e9937e2c82db165c | '''
Created on 2014/3/20
@author: Robert
'''
import wx
import wx.lib.newevent
import sys
import os
import threading
import logging
import time
####Thread event
myEVT_ThreadDone = wx.NewEventType()
EVT_ThreadDone = wx.PyEventBinder(myEVT_ThreadDone, 1)
myEVT_ThreadStart = wx.NewEventType()
EVT_ThreadStart = wx.PyEventBi... |
16,236 | 3492b074ba8cf0e0ec693763649b1c1884716f25 | from Tkinter import *
from threading import Thread
#from threading import Timer
from os.path import expanduser
import os
import time
import datetime
import tkFont
def recThread():
# os.system("sleep 1s;ffmpeg -f x11grab -s $(xdpyinfo | grep 'dimensions:' | awk '{print $2}' | cut -dx -f1)x$(xdpyinfo | grep 'dime... |
16,237 | 0cfaeada5b6c464e833fd34f80b00d4a27ae26bf | # sample usage
# python zip_file_password_cracker.py -f archive.zip -d dictionary.txt
import zipfile
import optparse
import os
from threading import Thread
def extract_file(archive, password):
try:
archive.extractall(pwd=password)
print '[+] Password = ' + password + '\n'
return
excep... |
16,238 | a1fce043bc1950020d778777d38e04691225e0ba | """
Description: Get GPS coordinates from labels (classification output)
Author: Iva
Date: 11/2/2016
Python version: 2.7.10 (venv2)
"""
from __future__ import division
import math
import numpy as np
from get_data.map_coverage import MercatorProjection, G_Point, G_LatLng
koef=1
MERCATOR_RANGE = 256... |
16,239 | 2871e79970f9ea9ff018e905144f19a5331e0356 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2019-09-27 18:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wally_trips', '0002_colors'),
]
operations = [
migrations.AddField(
... |
16,240 | 26372433b841211fd74ff5a95b44550bd23b7714 | from django.urls import path
from django.views.generic import TemplateView
from django.contrib.auth.decorators import login_required, permission_required
from .views import ItemView, CategoriaView, EncargadosListView, ItemDetailView, EncargadoDetailView
app_name = 'inventario'
urlpatterns = [
path(
'',
... |
16,241 | 4614e4b3457d613cbdbbdeec1dce6fb39acf90de | from Tests.test_crud import test_add_cheltuiala,test_delete_cheltuiala
from Tests.test_operatiuni import test_stergere_cheltuieli,test_adaugare_valoare_pt_o_data
from Tests.test_undo_redo import test_undo
def run_all_tests():
test_add_cheltuiala()
test_delete_cheltuiala()
test_stergere_cheltuieli()
... |
16,242 | 8ccc9a4806393d28e22d48f5dd1d46edb7404645 | class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
res = ""
carry = 0
if len(num1) <= len(num2):
for i in range(1,len(num1)+1):
carry, num = divmod(int(num1[-i])+int... |
16,243 | 877e36467e440186f8891279de63d1c5093d011e | ##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... |
16,244 | 92b30cb80f3f5ad6f0eea3a66f3b48b32b24877c | from .tboard import write_images, write_losses
from .weights import save_weights, load_weights |
16,245 | bc386b6c658dd34e9d6ecd85b255292d32f7d0f8 | #!/usr/bin/python
from sphero_driver import sphero_driver
from time import sleep
# if you know your Sphero's address
# sphero = sphero_driver.Sphero("Sphero", "FF:CD:AA:99:45:00")
sphero = sphero_driver.Sphero()
while not sphero.is_connected:
sphero.connect()
sleep(1)
sphero.set_rgb_led(255, 0, 0, 0, False)
sle... |
16,246 | b670b672ebf48715b179dae439cebbf20c018169 | '''
Created on Jun 9, 2017
@author: student
'''
# A program to average a set of numbers
# Illustrates interactive loop with two accumulators
def main():
my_sum = 0.0
count = 0
moredata = "yes"
while moredata[0] == "y":
x = input("Enter a number >> ")
my_sum = my_sum... |
16,247 | 37b1e2252f4d12565024f2d1f5c1ba66ebcb9b57 | from django.shortcuts import render,HttpResponse,redirect
import json
from weibo import models
from django.core.cache import cache
from io import BytesIO
import uuid
def userLogin(request):
if request.method == 'POST':
email = request.POST.get('email')
passwd = request.POST.get('passwd')
a... |
16,248 | 8e154c51612fb65234071e6454a0d6f5bff12a1e | import os
import pickle
import tarfile
import time
from .utils import download_dataset
import numpy as np
labels_list = [
"apple",
"aquarium_fish",
"baby",
"bear",
"beaver",
"bed",
"bee",
"beetle",
"bicycle",
"bottle",
"bowl",
"boy",
"bridge",
"bus",
"butte... |
16,249 | d7620ca25598775b75483a2f8f6311f65a4ba3a3 | '''
Module of Linux API for plyer.cpu.
'''
from os.path import join
from os import environ, listdir
from subprocess import Popen, PIPE
from plyer.facades import CPU
from plyer.utils import whereis_exe
class LinuxCPU(CPU):
'''
Implementation of Linux CPU API.
'''
def _sockets(self):
# physica... |
16,250 | 99cb7f09045362559513b195d8446cf52f19dfd7 | from __future__ import annotations
from dataclasses import dataclass
from typing import Optional, Deque
from collections import deque
@dataclass
class Node:
data: int
left: Optiona[Node] = None
right: Optiona[Node] = None
def inorder(root: Node):
result: list = []
def helper(root: Node):
... |
16,251 | 12d9c71cb32afd0f5ba3ebbcf578980389d966cf | # pylint: disable=all
import sys
class StationGraph(object):
"""
A stationgraph allows a graph data structure to be built by
passing in information one station at a time. From the graph's
perspective, each station would be considered a node in the graph. The
stationgraph is made of a nested dictionary arranged... |
16,252 | 02659ff5f9daaaa47d7530a5cde0788b2f3ba314 | # -*- coding: utf-8 -*-
import xml.etree.ElementTree as etree
import os.path, shutil
import gamelist, utils
import fav, dat
class BasicSorter :
def __init__(self,configuration,scriptDir,logger,bioses,setKey) :
self.configuration = configuration
self.scriptDir = scriptDir
... |
16,253 | 101750258189e874cf0ee54f5301954893c6bdcf | import argparse
import os
import random
import shutil
import time
import warnings
import numpy as np
from torchvision import datasets
from functions import *
from imagepreprocess import *
from model_init import *
from src.representation import *
import torch
import torch.nn as nn
import torch.nn.parallel
import torc... |
16,254 | 66e69404e9019e0714709abb34ba90576a62df1c | """
Checagens / Questionamentos
Usamos para checar se expressoes no codigo são validas ou não.
Podemos personalizar mensagens de erro.
SE UM PROGRAMA PYTHON FOR EXECUTADO COM O PARAMETRO -O, NENHU ASSERTION
SERÁ VALIDADO. OU SEJA , TODAS AS VALIDAÇÕES JÁ ERAM...
"""
#USANDO O ASSERT QUASE COMO SE FOSSE UM IF:
def so... |
16,255 | c1f5e583593854b1086bd394fce9ea3ff1b05ba5 | from scanners import SimpleScanner, TextScanner
from tokens import eof_token, null_token
# A tokenizer, the purpose of this class is to transform a markdown string
# into a list of "tokens". In this case, each token has a type and a value.
#
# Example:
# "_Hi!_" => [{type: UNDERSCORE, value: '_'}, {type: TEXT, value... |
16,256 | e724e4bff7fa61e6348e2decb6b1348c038c793e | class Solution(object):
def partition(self, head, x):
if head is None:
return None
result=l1=ListNode(0)
result1=l2=ListNode(0)
while head:
if head.val<x:
l1.next=head
l1=l1.next
else:
l2.next=head
l2=l2.next
head=head.next
l... |
16,257 | fb11d158ba2ced33bf302cd930f2deeafd2c7485 | from threading import local
_LOCAL = local()
class ThreadLocalCredentials:
def add(self, credentials):
_LOCAL.credentials = credentials
def authorize(self, http):
return _LOCAL.credentials.authorize(http) |
16,258 | 8085436ef991b07174269c03b674035df39c613d | ''' ===================== HYBRID SELECTION STRATEGY (HSS) ======================
Universidade Federal de Sao Carlos - UFSCar, Sorocaba - SP - Brazil
Master of Science Project Artificial Intelligence
Prof. Tiemi Christine Sakata (tiemi@ufscar.br)
Author: Vanessa Antunes ... |
16,259 | 94fd09e4ba6fbd0048cf5bb465bb7194ad3d9c1b | #
# Autogenerated by Thrift
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
# @generated
#
import typing as _typing
import folly.iobuf as _fbthrift_iobuf
import thrift.py3.builder
import module.types as _module_types
class InitialResponse_Builder(thrift.py3.builder.StructBuilder):
conten... |
16,260 | 85764ed6e00b138f67402af449d0e61aa3ff4724 | class CondaLockError(Exception):
"""
Generic conda-lock error.
"""
class PlatformValidationError(CondaLockError):
"""
Error that is thrown when trying to install a lockfile that was built
for a different platform.
"""
class MissingEnvVarError(CondaLockError):
"""
Error thrown if ... |
16,261 | 4a36130e91f4559047c640f99f96d3743a3bd647 | # -*- coding: utf-8 -*-
#
# Copyright 2017 Alexey Sanko
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
16,262 | b5a2f3a5c79ea59288df07e2be478eb46b3c368a | import allure
from common.basic_handler import Basic
@allure.feature("客户端用户相关接口")
class TestIndexContentController:
@allure.story("获取首页展示内容1")
def test_case1_get_home_page_content(self):
api_info = Basic().get_api_by_name("get_home_page_content")
content = Basic().send_request(**api... |
16,263 | adfaf82ae077bab189d433374528e333960b816e | # https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
from collections import deque
class Node:
# A utility function to create a new node
def __init__(self, key):
self.val = key
self.left = None
self.right = None
def levelOrder(root):
if root is None:
return []
... |
16,264 | 7a45b95d7c1327cabc07cb644416e41b4a296a4a | class GameState():
def tick(self, delta):
raise NotImplementedError("tick() is not implemented by its child")
def get_name(self):
raise NotImplementedError("get_name() is not implemented by its child")
|
16,265 | 66a8706a8a6a011ebfad9c709eb9eac9d315a7fe | #!/usr/bin/python3
# coding=utf-8
# pylint: disable=I0011,W1401,E0401,R0914,R0915,R0912,C0103
# Copyright 2019 getcarrier.io
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... |
16,266 | 9e8ecbcddcb360db5a9abd407762ddf04e8b7c2f | import string_ques
str1 = "aa bb cc"
str2 = "asodf"
str_func_obj = string_ques.StringFunctions(str1, str2)
print("Test for unique Characters in a string:")
print(str_func_obj.hasUniqueChars())
print("Test for permutation in two strings:")
print(str_func_obj.stringPermutation())
print("urilifying a string:")
print(... |
16,267 | da9d55487c82ff81edfc2288df32b71f38a29b7c | #!/usr/bin/python3
#coding: utf-8
# Este código pode ser otimizado
# Foi desenvolvido para correr em Linux
# Esta versão utilizando queues e threadpoolsexecutor ainda está em desenvolvimento
# Um dos desafios é fazer a barra de progresso para as threads em execução versus as terminadas
# Importar bibliotecas
import ra... |
16,268 | 3d80ea434da7042df04895f184ac513508491ed8 | # Generated by Django 3.0.3 on 2020-02-17 10:20
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('job', '0005_auto_20200215_0638'),
]
operations = [
migrations.RenameField(
model_name='company',
old_name='contact_email',
... |
16,269 | 1c2b3c8250f90ce9875b1a063ed6315b0f28b31a | import wx
from ObjectListView import ObjectListView, ColumnDefn
from openpyxl import load_workbook
from app.controller.load_data_dialog import load_and_convert
class LoadDataDialog(wx.Dialog):
def __init__(self, parent, pathName='', **kwargs):
super(LoadDataDialog, self).__init__(parent, **kwargs)
... |
16,270 | a8d8f308c3e52a8fc828db2e6806d8b10a965e5b | import wx
class MainFrame(wx.Frame):
def __init__(self,p,t):
wx.Frame.__init__(self,id=-1,parent=p,size=(260,300),title=t)
panel=wx.Panel(self,-1)
self.label1 = wx.StaticText(parent=panel,
id=-1,
size=(40, 58),
... |
16,271 | d6222732471966971044d991601167b2f68f4340 | import torch
import numpy as np
import torch.nn as nn
import math
from ...utils import center_utils, box_utils, common_utils
from ..model_utils import model_nms_utils
from ...ops.roiaware_pool3d import roiaware_pool3d_utils
def draw_heatmap(heatmap, boxes):
raise NotImplementedError
def _gather_fea... |
16,272 | 6af1c993dd32a788c625047f63f24905cecaf276 |
def rodCutting(price,totallength):
temp = [0]*(len(price)+1)
for i in range(1,len(price)+1):
for j in range(i,len(price)+1):
temp[j] = max(temp[j] , temp[j-i]+price[i-1])
print (temp)
return None
print(rodCutting([2,5,7,8],5)) |
16,273 | 685c427319b57eb546cffdc29f16430849249288 | from app import app
from flask import render_template, redirect, url_for, flash, request
from flask_login import current_user, login_user, logout_user, login_required
from app.models import User, Post, Borda
from app import db
from app.forms import RegistrationForm, LoginForm, PostForm, BoardForm
from werkzeug.urls imp... |
16,274 | 62d5059149e3373028d2bc0bc5ef478dfa9a70f5 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from collections import OrderedDict
import inspect
import re
from rest_framework.fields import empty, Field as SerializerField
from rest_framework.relations import RelatedField
from django_filters.filters import Filter as DjangoFilterFiel... |
16,275 | ef51150fccd35ec4ce118aed1cf45acb8ee0ec0e | #!/oasis/scratch/csd181/mdburns/python/bin/python
# Copyright (C) 2012 Matthew Burns <mdburns@ucsd.edu>
from datetime import datetime
import helpers
import helpers.float_open as fop
from scipy import stats, zeros, ones, signal
from scipy.io import loadmat, savemat
import numpy as np
from numpy import array
import os
... |
16,276 | 7819e5b3fc142645fa3bd545f44c70ee721b99f8 | from unittest import mock
from know_me.profile import serializers, views
@mock.patch("know_me.profile.views.DRYPermissions.has_permission")
@mock.patch(
"know_me.profile.views.permissions.HasListEntryListPermissions.has_permission" # noqa
)
def test_check_permissions(mock_list_permissions, mock_dry_permissions)... |
16,277 | f1b3fb2fb0cc380c16087991bec5b03d98de013a | #!/usr/bin/env python
from distutils.core import setup
setup(
name='provisor',
version='0.2',
packages=['provisor'],
scripts=[
'bin/provisor-server',
'bin/provisor-create',
'bin/provisor-config'
],
data_files=[('/etc',['provisor.conf'])],
author='Hashbang Team',
... |
16,278 | 0e66979977c06ecddc6ea13c75073684c4a86a17 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import matplotlib.pyplot as plt
import tensorflow as tf
# 读取图片
image_data = tf.gfile.FastGFile("data/dog3.jpg", 'br').read()
#
with tf.Session() as sess:
img_data = tf.image.decode_jpeg(image_data)
plt.imshow(img_data.eval())
plt.show()
# 将图片数据转换成实数类型
... |
16,279 | a4b16f65894d994815628fbfd146115e32c18c2d | from serializer import UserSerializer
class NeonUserMiddleware(object):
def process_request(self, request):
if request.user.is_authenticated():
request.user.user_json = UserSerializer(request.user,many=False).data
return None |
16,280 | 8eefafb3c00af6ab0d6d97727f562131bfb1ffe0 | import matplotlib.pyplot as plt
from matplotlib import pylab
import numpy as np
import json
APRCH_PATH = './results/approach_test/'
CWT_PATH = './results/context_window_test/'
# Training Output Parsing
def parse_approach_test_results(filenames):
'''
Parses results from an architecture test given result filena... |
16,281 | f0b2366aaf1908d0ddfbe0e8ef083bafd5b33d8f | # -*- coding: utf8 -*-
# ============LICENSE_START=======================================================
# org.onap.vvp/validation-scripts
# ===================================================================
# Copyright © 2019 AT&T Intellectual Property. All rights reserved.
# ========================================... |
16,282 | d000679ddecf863cc24a1835e1ea5ab84ef4263a | print("Assalamualaikum")
print("Ayo semangat") |
16,283 | aafa99eb7742165ee4a64897e5d9cf2e597cde56 |
import requests
import os
response = requests.get('https://api.github.com/users/<repo_name>/repos').json() #####getting the whole response containing every detail of all repos
for repo in response:
url=str(repo['html_url'])######using this to parse the html url of therepo
cmd='git clone '+url ####adding it t... |
16,284 | aa484cae880de326e852c5bb292bf030325955e2 | from collections import OrderedDict
class Transacao:
def __init__(self, remetente, destinatario, valor):
self.remetente = remetente
self.destinatario = destinatario
self.valor = valor
def dict_ordenado(self):
return OrderedDict([('remetente', self.remetente),('destinatario', se... |
16,285 | b116a26312998b52c7a095e681e5aa396c687088 | import collections
import heapq
import re
ipset = set()
prodcount = collections.defaultdict(int)
ipv4_pattern = re.compile("^(([01]?[0-9][0-9]?|25[0-5]|2[0-4][0-9]|)\\.){3}([01]?[0-9][0-9]?|25[0-5]|2[0-4][0-9]|)$")
file = open('weblog.txt', 'r')
for line in file:
words = line.split()
for word in words:
... |
16,286 | 5513ca4cbd3d9e5ea3ad3c2e84862ecfb9327e07 | # Chapter 7 - Reading Files
# OPENING A FILE
# before we can read the contents of the file, we must tell Python which file we are going to work with and what we will be doing with the file
# this is done with the 'open()' function
# open() returns a "file handle" - a variable used to perform operations on the file
# S... |
16,287 | 2f427aa8740845d173872f21f9d9a36f9b03220f | from django.db import models
from accounts.models import Profile
# Create your models here.
class ContactMessage(models.Model):
sender = models.ForeignKey(Profile, on_delete=models.DO_NOTHING)
subject = models.CharField(max_length=200)
email = models.EmailField()
body = models.TextField()
def __str__(self):
re... |
16,288 | b871b2019cfe1d984dbb9f27240c1bf84d16b406 | """
Unit and regression test for the openff_nagl_models package.
"""
import glob
import os
from pkg_resources import resource_filename
import pytest
from openff.nagl_models import validate_nagl_model_path, list_available_nagl_models
def find_model_files():
pattern = resource_filename('openff.nagl_models', 'mod... |
16,289 | 3bca927a2478c9c9fd458b72b80dc0f7a4551f58 | import sys
_module = sys.modules[__name__]
del sys
main = _module
src = _module
client = _module
models = _module
server = _module
utils = _module
from _paritybench_helpers import _mock_config, patch_functional
from unittest.mock import mock_open, MagicMock
from torch.autograd import Function
from torch.nn import Modu... |
16,290 | 1ebadfcec17b6f68f82dc4f97449486dffde4151 | from setuptools import setup,find_packages
setup(name= "pixellib",
version='0.6.6',
description='PixelLib is a library used for easy implementation of semantic and instance segmentation of objects in images and videos with few lines of code.PixelLib makes it possible to train a custom segmentation mode... |
16,291 | 0f24ef96cf82ffafee278f4c5a4cf252d34090da | from django import forms
class PoetryForm(forms.Form):
poetry_seed = forms.CharField(label='Poetry seed')
n_words = forms.IntegerField() |
16,292 | 5562d872961516fdf036ea0118ba070298b64f00 | """
airPy is a flight controller based on pyboard and written in micropython.
The MIT License (MIT)
Copyright (c) 2016 Fabrizio Scimia, fabrizio.scimia@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in... |
16,293 | b101ad7eff2cf7007509d640b7828cfbd3e40748 | from .curry import curry
from .reduce import reduce
@curry
def apply(fn, args):
return fn(*args)
|
16,294 | 7f8c042600a0899f6d16754726aad39cbe3998a9 | # -*- coding: utf-8 -*-
import datetime, pytz
import dateutil, dateutil.tz, dateutil.parser
import logging
class Date:
def isAware(self, date):
"""
Tiene zona definida?
"""
return (date.tzinfo != None) and (date.tzinfo.utcoffset(date) != None)
def isNaive(self, date... |
16,295 | 7da967cefed4c62902107c45ba31cd0c5d9f425d | import wpilib
from wpilib import RobotDrive
driveTrain = None
def init(driveMotors):
global driveTrain
driveTrain = wpilib.RobotDrive(**driveMotors)
driveTrain.setExpiration(0.2)
driveTrain.setSafetyEnabled(False) |
16,296 | 3ace4cedd67ecddd7ff66241d2fe47650c8a59ee | '''
Curva - A module for Elliptic-Curve Integrated Encryption Scheme (ECIES) based on AES and HKDF.
This module also provides interfaces for Elliptic-Curve Diffie-Hellman (ECDH) and Elliptic-Curve Digital Signature Algorithm (ECDSA).
The only interface exposed to the user is Curva, which integrates all functions m... |
16,297 | fb8a0df34a52355a421f6ce2f74bae52d7ef25a1 | # 58A - Chat room
# http://codeforces.com/problemset/problem/58/A
import re
s = input()
if re.match(r'.*h.*e.*l.*l.*o.*', s):
print('YES')
else:
print('NO')
|
16,298 | c48f402ca02ab7d1b37acce916fcc5025d97dfa7 | # -*- coding: utf-8 -*-
#
# Telefónica Digital - Product Development and Innovation
#
# THIS CODE AND INFORMATION ARE PROVIDED 'AS IS' WITHOUT WARRANTY OF ANY KIND,
# EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
#
# Copyri... |
16,299 | de68725fe5d3042304465f421c25b7c58fc13a34 | from django import forms
from captcha.fields import CaptchaField
class CaptchaForm(forms.Form):
captcha = CaptchaField()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.