index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
5,500 | 1ccaedb6e79101764db1907634ba627a0f9f2bb2 | class Solution(object):
def maxSubArrayLen(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
sums = [0] * (len(nums) + 1)
seen = {}
seen[0] = -1
res = 0
for idx, n in enumerate(nums):
sums[idx +... |
5,501 | 9539d2a4da87af1ff90b83bbcf72dfc8ab7b6db0 | """Unit tests for the `esmvalcore.preprocessor._rolling_window` function."""
import unittest
import iris.coords
import iris.exceptions
import numpy as np
from cf_units import Unit
from iris.cube import Cube
from numpy.testing import assert_equal
from esmvalcore.preprocessor._rolling_window import rolling_window_stati... |
5,502 | 1530f1711be6313b07df680721daf4cb0a84edc0 | # ------------------------------------------------------------
# calclex.py
#
# tokenizer for a simple expression evaluator for
# numbers and +,-,*,/
# ------------------------------------------------------------
import ply.lex as lex
# Regular expression rules for simple tokens
t_PLUS = r'\+'
t_MINUS = r'-'... |
5,503 | 8e1de62f2490d2276a834ae1ab0f1958649fa821 | # 938. Range Sum of BST
# Share
# Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
# The binary search tree is guaranteed to have unique values.
# Example 1:
# Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
# Output: 32
# Example 2:
... |
5,504 | d0f83e3b7eb5e1bc81a56e46043f394757437af8 | from django.db import models
# Create your models here.
class GeneralInformation(models.Model):
name = models.CharField(max_length=100)
address = models.TextField()
city = models.CharField(max_length=20)
class Meta:
ordering = ['name']
def __str__(self):
return "{} {} {}".format... |
5,505 | 5251724656e1d971900fff3d8fa0210c6cfc27bb | n=int(0)
import random
def doubleEven(n):
if n % 2 == 0:
n = n*2
return (n)
else:
return "-1"
print(doubleEven(n = int(input("put in a number"))))
g=int(0)
def grade(g):
if g < 50:
return "F"
if g < 66:
return "C"
if g > 92:
return "A+"
else:
... |
5,506 | 53fd020946a2baddb1bb0463d2a56744de6e3822 | #List methods allow you to modify lists. The following are some list methods for you to practice with. Feel free to google resources to help you with this assignment.
#append(element) adds a single element to the list
#1. 'Anonymous' is also deserving to be in the hacker legends list. Add him in to the hacker legends ... |
5,507 | a1d1056f302cf7bc050537dd8cc53cdb2da7e989 |
#calss header
class _PULPIER():
def __init__(self,):
self.name = "PULPIER"
self.definitions = pulpy
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.basic = ['pulpy']
|
5,508 | 4ae611ee8c019c76bb5d7c1d733ffb4bd06e2e8d | # import random module from Python standard library
# define a dictionary with image urls and number of flucks
# set the served img variable to be a random element from imgs
# hints:
# to put dict keys in a list: list(dict.keys())
# to choose a random item from a list: random.choice(lst)
# keep asking user if they ... |
5,509 | 0470f98247f8f835c0c052b01ddd7f1f7a515ab5 | #-*- coding:utf-8 -*-
from xml.etree import ElementTree
from xml.etree.ElementTree import Element
_exception = None
import os
class xmlSp:
def addNode(self,parentNode,childNode):
parentNode.append(childNode)
def createChildNode(self,key,value,propertyMap={}):
element... |
5,510 | 4d31985cf1266619406d79a7dbae269c10f21bda | import world
import items
class Quest:
def __init__(self):
raise NotImplementedError("Do not create raw quest classes")
def __str__(self):
return self.quest_name
def give_reward(self, player):
print("You receive: \n{} gold\n{} exp".format(self.reward_gold, self.reward_exp))
for item in self.reward_it... |
5,511 | 399097ef7cfdc061b307c3cc29615c9f50b1e6bf | from utils.gradient_strategy.dct_generator import DCTGenerator
from utils.gradient_strategy.random_generator import RandomGenerator
from utils.gradient_strategy.upsample_generator import UpSampleGenerator
from utils.gradient_strategy.centerconv_generator import CenterConvGenerator
from utils.attack_setting import *
fro... |
5,512 | 117b340b13b9b1c53d3df1646cd5924f0118ab5d | #Small enough? - Beginner
# You will be given an array and a limit value.
# You must check that all values in the array are
# below or equal to the limit value. If they are,
# return true. Else, return false.
def small_enough(array, limit):
counter = ""
for arr in array:
if arr <= limit:
... |
5,513 | 70b26052d9516fd067ff71074a6dc4c58ace7d80 | # 選択肢が書き換えられないようにlistではなくtupleを使う
chose_from_two = ('A', 'B', 'C')
answer = []
answer.append('A')
answer.append('C')
print(chose_from_two)
# ('A', 'B', 'C')
print(answer)
# ['A', 'C'] |
5,514 | 9928eaa32468453f405d8bb650f3e0e85a7933bf | import os
import cv2
import numpy as np
import torch
import torch.utils.data
import torchvision
from torchvision import transforms
from utils.utils import loadYaml
from .base_datalayer import BaseDataLayer
import albumentations as albu
class Datalayer(BaseDataLayer):
def __init__(self, config, augmentation=None,... |
5,515 | 855bfc9420a5d5031cc673231cc7993ac67df076 | import numpy as np
import h5py
def rotate_z(theta, x):
theta = np.expand_dims(theta, 1)
outz = np.expand_dims(x[:, :, 2], 2)
sin_t = np.sin(theta)
cos_t = np.cos(theta)
xx = np.expand_dims(x[:, :, 0], 2)
yy = np.expand_dims(x[:, :, 1], 2)
outx = cos_t * xx - sin_t * yy
outy = sin_t * x... |
5,516 | 22792937415a8ee4cecff2a9683c435abe54bdab | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright © 2020- Spyder Project Contributors
#
# Released under the terms of the MIT License
# ----------------------------------------------------------------------------
"""Tests for the execution of pylint."""
... |
5,517 | 520b9246c3c617b18ca57f31ff51051cc3ff51ca | from abc import ABC, abstractmethod
class Shape(ABC): # Shape is a child class of ABC
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Square(Shape):
def __init__(self, length):
self.length = length
square = Square(4)
# this will co... |
5,518 | c28d7fc45be9a6efa7b7ef00520898c3d238ac63 | a=raw_input("Enter the column\n")
b=raw_input("Enter the row\n")
i=0
k=0
m=0
c=""
d=""
while (m<int(b)):
while(i<int(a)):
c=c+" "
for j in xrange(1,4):
c=c+"-"
i=i+1
while(k<int(a)):
d=d+"|"
for l in xrange(1,4):
d=d+" "
k=k+1
m=m+1
... |
5,519 | b573db8ea0845fb947636b8d82ed462904c6005d | import boto3
from app.models import *
from app.config import *
from app.lib.log import save_races_to_db, save_laptimes_to_db
from app.utils.utils import get_sec
import pandas as pd
def import_csv_from_aws():
client = boto3.client(
's3',
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCE... |
5,520 | e58dbb4f67c93abf3564dc0f38df8852313338f0 | import time
import jax.numpy as jnp
def tick():
return time.perf_counter()
def tock(t0, dat=None):
if dat is not None:
try:
_ = dat.block_until_ready()
except AttributeError:
_ = jnp.array(dat).block_until_ready()
return time.perf_counter() - t0
|
5,521 | 083a9555f8db586fbb065d59e4e333bb16ee3d2a | import os
import sys
from subprocess import check_output
from charmhelpers.fetch import (
apt_install,
apt_update,
add_source,
)
from charmhelpers.core.templating import render
from charmhelpers.contrib.database.mysql import MySQLHelper
def install_mysql(package='mysql-server', sources=None, keys=None)... |
5,522 | b2371f9c774c605a52ff1a4fae2dd44a856076aa | no=int(input("enter no:"))
rev=0
while no!=0:
r=no%10
no=no//10
rev=rev*10+r
print("reverse no is:",rev)
|
5,523 | 2da10163a40c9720ca9deecd9afb0e39aa885546 | from tkinter import *
from PIL import ImageTk,Image
import sys, os
# This will display images and icon
root = Tk()
root.title("Expanding GUI")
# With ubuntu, it did not work the icon part
#root.iconbitmap('@/home/gxgarciat/Documents/Tkinter/gdrive.ico')
#root.iconphoto(True, PhotoImage(file="@/home/gxgarciat/Docume... |
5,524 | d805a1290c107a8d768417a432e338b182b7cd6b | import numpy as np
class LinearRegressor():
def __init__(self, alpha=0.1, epochs=1):
self.alpha = alpha
self.epochs = epochs
self.costs = []
self.theta = None
def _cost_function(self, y_pred, y, m):
"""
Gets the cost for the predicted values when contrasted wit... |
5,525 | 1fe6fab717a77f13ddf7059ef0a5aaef217f0fb0 | class Solution:
def search(self, nums: List[int], target: int) -> int:
n = len(nums)
left, right = 0, n-1
found = False
res = None
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
found = True
... |
5,526 | 64bbf2e3b961a6e0b5d7e551278bb21990df2ed9 | import uuid
from fastapi import APIRouter, Depends, HTTPException, Form, Body
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
# dependency
from configs.config_sqlalchemy import get_db
# schema
from schema import store_schema
# define the url the clie... |
5,527 | 4daab8b8db1e394e3132ab5550fe0236b67074d8 | from helper import *
tree_type = TREE_TYPE_SPLIT
file_name = ''
file_path = ''
split_scalars = {}
visited = {}
adjacency = {}
pairs = {}
index_map = {}
postorder_map = {}
preorder_map = {}
birth = {}
death = {}
string = ''
class Tree(object):
def __init__(self):
self.index = None
self.children = []
self.p... |
5,528 | 6cc23a3e2fa3b1baddf05b30a1054a7faf0371a6 | # -*- coding: utf-8 -*-
from .base import BaseSchema
from marshmallow import fields
class BaseTickSchema(BaseSchema):
"""
Time : 时间
High : 最高价
Low : 最低价
Volume : 交易量
Last : 最新价
"""
Time = fields.String()
High = fields.String()
Low = ... |
5,529 | 530c2c185e57ffd3ac64628fc9f7f7985b0480fe | #!/usr/bin/env python
import numpy as np
import time, random
import sys, os, struct, socket
import psycopg2
import test_coords
import alex_random
import new_sim_utils
import sdr_kml_writer
from geo_utils import geo_utils
from beacon import beacon
from sim_data import data_utils
ENABLE_JITTER = False
ENABLE_DROPPED_... |
5,530 | 25ce31aee44c80ce4a5c1af7d1ca12c73c14df47 | from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(auto_now_add=timezone.now)
autho... |
5,531 | 4df747b3ff254e0ccc4483acd7be12f3441bbcd8 |
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So, you're %r old, %r tall, and %r heavy." % (age, height, weight)
#raw_input does not exist in Python 3.x while input() does. raw_input() returns a string, and inp... |
5,532 | 505689803c8f4490619ab1a7579fde1e2c18c538 | from datetime import datetime
import struct
BEACON_LENGTH = 84
EPS_LENGTH = 20
COM_LENGTH = 10
# reverse engineered
ADCS1_LENGTH = 7
ADCS2_LENGTH = 6
AIS_LENGTH = 20
class EPS(object):
def __init__(self, eps_data):
if len(eps_data) != EPS_LENGTH:
raise InputException(len(eps_data), EPS_LENGTH... |
5,533 | a99426c0751885f17078e709fd523cf3a26f5286 | '''
sin(x) = x^1/1! - x^3/3! + x^5/5! - x^7/7! + …..
Input : x, n ( No. of terms I want in series )
Input : 3.14, 10
Output : sin(3.14) = sin(180) = 0
Radians vs Degrees
( 0, 30, 60, 90 ….)
2pi = 360
Pi = 180
Pseudo code :
1.Take input variables radians,num
2. sin = 0
3. Indices = 1
4. odd = 1
4... |
5,534 | 04b02931b749ad06a512b78ca5661ae1f5cb8a9c | from random import randint
from Ball import Ball
from Util import Vector, Rectangle
class Player:
RADIUS = 10
COLOR1 = "#80d6ff"
COLOR2 = "#ff867c"
OUTLINE = "#000000"
@property
def right(self):
return self.pos.sub(Vector(Player.RADIUS, 0))
@property
def left(self):
... |
5,535 | be5a683309317f1f6ebc20ad3511fd2b2510e806 | from django.http.response import HttpResponse
from django.shortcuts import render , HttpResponse
import requests
from django.conf import settings
from .forms import WeatherForm
# Create your views here.
def get_weather(request):
form = WeatherForm()
error = ""
output = {}
if request.method == 'POST':
... |
5,536 | ba94a69ac356969ab593afc922a2517f4713771f | __title__ = 'FUCKTHEINTRUDERS'
__description__ = 'Checking for Intruders in my locality'
__version__ = '0.0.1'
__author__ = 'Shivam Jalotra'
__email__ = 'shivam_11710495@nitkkr.ac.in'
__license__ = 'MIT 1.0'
|
5,537 | a638504737d0069d4fa40b0fc5026203904563e8 | from decimal import Decimal
from django.conf import settings
from blood.models import Bank, Blood
class Cart(object):
def __init__(self, request):
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
cart = self.session[settings.CART_SES... |
5,538 | 3beaea1f2b1b085a60bdc5e53f4e6d9aff7e8b6f | import cv2,os
import sqlite3
cam = cv2.VideoCapture(0)
detector = cv2.CascadeClassifier('Classifiers/face.xml')
i = 0
offset = 50
def create_or_open_db(db_file):
db_is_new = not os.path.exists(db_file)
conn = sqlite3.connect(db_file)
if db_is_new:
print 'Creating schema'
sql = '''create ta... |
5,539 | 88542a18d98a215f58333f5dd2bf5c4b0d37f32f | x = 5
print(x , " "*3 , "5")
print("{:20d}".format(x))
|
5,540 | acf409f2e56cd16b7dc07476b49b9c18675f7775 | from PIL import Image
from flask_restplus import Namespace, Resource
from werkzeug.datastructures import FileStorage
from core.models.depthinthewild import DepthInTheWild
from core.utils import serve_pil_image
api = Namespace('nyudepth', description='Models Trained on NYUDepth')
upload_parser = api.parser()
upload_p... |
5,541 | 0295d6ba962d099e76110c7a0e39748e3163e300 | #!/usr/bin/env python
###########################################################################
# 1) connect to the MQTT broker
# 2) subscribe to the available data streams
# 3) log to google sheets
# 4) notify on critical events on the telegram channel
###############################################################... |
5,542 | 0544c67cb14549e32b6ff8ea3215c6c65c8416ec | from typing import Any
from electionguard.ballot import CiphertextAcceptedBallot
from electionguard.decryption import compute_decryption_share_for_ballot
from electionguard.election import CiphertextElectionContext
from electionguard.scheduler import Scheduler
from electionguard.serializable import write_json_object
fr... |
5,543 | 7e9efb267a5464a6e53f81f63d82c28acba8bc8c | # ToDo:
"""
965. Univalued Binary Tree
Easy
A binary tree is univalued if every node in the tree has the same value.
Return true if and only if the given tree is univalued.
Note:
The number of nodes in the given tree will be in the range [1, 100].
Each node's value will be an integer in the range [0, 99].
... |
5,544 | ddf64ea5ecbd3aa737cd788924035cccb5544fec | ## adapted from https://matplotlib.org/examples/api/radar_chart.html
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.spines import Spine
from matplotlib.projections.polar import PolarAxes
from matplotlib.projections import register_projection
def radar_factory(num... |
5,545 | 225687729b64f455bcc841e83105c7444efdfad3 | import math as m
def calcula_elongacao(A, ϕ, ω, t):
x = A * m.cos(ϕ + ϕ * t )
return x |
5,546 | 54ed0683d0f8d907c27e2f3809f9533556593392 | import json
from pets.pet import Pet
from store_requests.store import Store
from user_requests.user import User
SUCCESS = 200
NotFound = 404
url_site = 'https://petstore.swagger.io/v2'
new_username = "Khrystyna"
new_id = 12345
invalid_new_id = 1234
error_message = "oops we have a problem!"
store_inventory = {
"1": ... |
5,547 | 918358f6e8e3f1c601b18a3c08fc6b7c024721ba | password = '#Garb1122' |
5,548 | 04e57739e6fb98cd237fbe09caecd17c728c1797 | # terrascript/external/__init__.py
import terrascript
class external(terrascript.Provider):
pass |
5,549 | 1396509f65d194eeaefa3841e152b7078abf0032 | import sys
class Bus:
def __init__(self):
self.seats=0
self.dict_seats={}
self.num_passenger = 0
def conctructor(self,seats):
self.seats=seats
for i in range(1,self.seats+1):
self.dict_seats.update({i:"Free"})
return self.dict_seats
def getOn(sel... |
5,550 | e77e0791ddf211807566528e9532eebb54db43b5 | from abc import ABC, abstractmethod
from datetime import datetime, timedelta, date
import os
import housekeeper
import yfinance as yf
import pandas as pd
class DataManager(ABC):
def __init__(self):
self.__myHousekeeper = housekeeper.instance_class()
self.__config_filename = "tickers... |
5,551 | 3e1c2d0c5bb30d093a99f10020af14db5436bf02 | # -*- coding: utf-8 -*-
"""microcms package, minimalistic flatpage enhancement.
THIS SOFTWARE IS UNDER BSD LICENSE.
Copyright (c) 2010-2012 Daniele Tricoli <eriol@mornie.org>
Read LICENSE for more informations.
"""
VERSION = (0, 2, 0)
|
5,552 | 844b8e2d4f05a51282b356c995f2733d6935a5d6 | # We will try to implement add noise to audio file and filter it using Mean and Median Filters.
import numpy as np
import scipy
import matplotlib.pyplot as plt
from scipy.io.wavfile import read
from scipy.io.wavfile import write
rate,audio_original = read('Audio_Original.wav')
audio = audio_original[:,0]
write("Audi... |
5,553 | 9bf8834b12bcace0f6daf64adae1babe78bb04fa | '''
Created on Nov 1, 2013
@author: hanchensu
'''
from numpy import *
import numpy as np
def smoSimple(dataMatIn, classLabels, C, toler, maxIter):
dataMatrix = mat(dataMatIn); labelMat = mat(classLabels).transpose()
b = 0; m,n = shape(dataMatrix)
matrix = mat([[1,2],[3,4],[5,6]])
m,n= shape(matrix)
matA = mat... |
5,554 | 92b24fe82929ed4590e5350188673c2245136d03 | from db import do_command, do_command_no_return, do_insert
def get_grocery(upc):
cmd = "SELECT name FROM grocery WHERE upc = ?"
rtVal = do_command(cmd, [upc])
length = len(rtVal)
if length > 0:
return {'success': bool(len(rtVal)), 'grocery': rtVal[0]}
return {'success': bool(len(rtVal))... |
5,555 | b21796a9e10314f80cac3151d1fdbb139966303f | import numpy as np
import scipy.io as sio
import os
import torch
from torchvision.utils import save_image
from tools import *
def test(config, base, loaders, brief):
compute_and_save_features(base, loaders)
results = evalutate(config, base, brief)
return results
def evalutate(config, base, brief=False):
re... |
5,556 | 02381f28ef20aa0c2c235ef6563e1810a5931e35 | from qiskit import QuantumCircuit,execute,Aer
from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt
qc_ha=QuantumCircuit(4,2)
qc_ha.x(0)
qc_ha.x(1)
qc_ha.barrier()
qc_ha.cx(0,2)
qc_ha.cx(1,2)
qc_ha.ccx(0,1,3)
qc_ha.barrier()
qc_ha.measure(2,0)
qc_ha.measure(3,1)
#qc_ha.draw(output='mpl')
coun... |
5,557 | 539726df0e631c7a8edabf50fd739ee0497e3e97 | from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression, Lasso, Ridge
from sklearn import tree
import pickle as pk
X = pk.load(file=open('../data/temp/train.pkl', 'rb'))
y = pk.load(file=open('../data/temp/label.pkl', 'rb'))
X_train, X_test, y_train, y_test = train_test_... |
5,558 | ff358136bc96fa7f3eb41d019ddfd10fc4db8f0d | class Person:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
def GetName(self):
return (self.fname + ' ' + self.lname)
|
5,559 | f6fe33e04ccdca1d9714caec412478d0cfc8b363 | from flask import Flask, request
from flask import render_template
import sqlite3
import datetime
app = Flask(__name__)
@app.route('/')
def index(date = ""):
date = request.args.get('date')
if not date:
now = datetime.datetime.now()
date = "%02d.%02d.%04d" % (now.day, now.month, now.year)
... |
5,560 | 89d0d5d13c5106c504c6727c7784f048a30495dc | # Generated by Django 3.2 on 2021-05-22 06:54
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Recuerdos',
fields=[
('id', models.BigAutoFie... |
5,561 | c418b9b6903ebdad204a3a55f2384a94a3be0d09 | """
Pattern matching problem
Boyer Moore algorithm
First is my attempt, below is the code provided in the book
Idea:
Optimize brute force approach using 2 heuristics:
- Looking-Glass: start searches from last character of the
pattern and work backwards
- Character-Jump: During testing of a pattern P, a mismatch
in T[i... |
5,562 | af00c6f443426b1f61e1816d7d14ebc7e6871a82 | import csv
import us
from flask import abort, Flask, request, render_template
app = Flask(__name__) # pylint: disable=invalid-name
@app.route('/')
def root():
return render_template('index.html')
@app.route('/api')
def index():
return render_template('index.html')
@app.route('/api/total/counties')
def ... |
5,563 | ac1d38f550e548dff6ba226dbfc3dd1e5ff876a8 | from django.db import models
from django.contrib.gis.db import models
from django.contrib.auth.models import User
from django.urls import reverse
class Project(models.Model):
actual_developer = models.ForeignKey(User,null = True,blank=True, on_delete=models.CASCADE)
# actual_developer = models.CharField(User,null ... |
5,564 | 65ea40ad1c1bf6bf23aed5316b91862c9cdc353d | __author__ = "Rick Sherman"
__credits__ = "Jeremy Schulman, Nitin Kumar"
import unittest
from nose.plugins.attrib import attr
from jnpr.junos import Device
from jnpr.junos.utils.scp import SCP
from mock import patch
@attr('unit')
class TestScp(unittest.TestCase):
def setUp(self):
self.dev = Device(host... |
5,565 | 75ef5dd2b82cf79819f18045559f9850c74bb55a | from flask import Blueprint, request, make_response
from flask_expects_json import expects_json
from server.validation.schemas import guest_calendar_schema
from tools.for_db.work_with_booking_info import add_booking_info_and_get_uuid
from tools.for_db.work_with_links import get_link
from tools.build_response import bu... |
5,566 | 5261346f96e7520b6ef75a292b3d44a6f00d868c | # Imports
from __future__ import print_function
import numpy
from numpy.random import randint
from enum import Enum
__all__ = ["common", "plot"]
class result(Enum):
CRIT = 16
HIT = 8
EVADE = 4
FOCUS = 2
BLANK = 1
def result_str(res):
str = ""
if res & result.BLANK:
str += "BLANK"
i... |
5,567 | 137842d50355563b2df6c2fc48864c01a22afa80 | # -*- coding:utf-8 -*-
# pylint: disable=line-too-long
_BASE_REPRESENTATIONS = [
"Primitive(field='f1', op='eq', value='value')",
"Primitive(field='f1', op='eq', value=42)",
"Primitive(field='f1', op='eq', value=3.14)",
"Primitive(field='f1', op='eq', value=True)",
"Condition(op=Operator.OR, values... |
5,568 | 1605396a6edb31dd6fe9238a0506f8cfeb794d07 | def play_43():
n=int(input('Enter n :'))
l=[]
for i in range(n):
l.append(int(input()))
for i in range(n-1):
for j in range(i+1,n):
if l[i]<l[j]:
continue
return "no"
return "Yes"
play_43()
|
5,569 | 2de62c73507acac597d70557adfe8286e2f28a1f | def assert_number(arg):
if not isinstance(arg, (int, float)):
raise TypeError(f"Expected number, got {type(arg)}")
|
5,570 | 788d9fa03c4311a8077d492b1a2b06d1f88826a3 | import numpy as np
import torch
def pad_sequences_1d(sequences, dtype=torch.long, device=torch.device("cpu"), fixed_length=None):
""" Pad a single-nested list or a sequence of n-d array (torch.tensor or np.ndarray)
into a (n+1)-d array, only allow the first dim has variable lengths.
Args:
sequence... |
5,571 | dfc412acc9b69f50396680db1b9f6feafe162996 | import io
import os
from flask import Flask
from werkzeug.datastructures import FileStorage
import pytest
PNG_FILE = os.path.join(os.path.dirname(__file__), 'flask.png')
JPG_FILE = os.path.join(os.path.dirname(__file__), 'flask.jpg')
class TestConfig:
TESTING = True
MONGODB_DB = 'flask-fs-test'
MONGODB... |
5,572 | c80ecb97c8863b724169715b766024ce824b9225 | import numpy as np
# UM TRABALHO FEITO PELA GRANDE DUPLA PEQUENA Mag e Rud
def main():
a = int(input("Informe a sua opção (Aleatório = 0, Você escolhe = outro numero): "))
if(a != 0):
linhas = int(input("Informe o número de linhas da matriz: "))
colunas = int(input("Informe o número de colunas... |
5,573 | 0f4bdaecef356e01cbef527d4886564d9ef840fa | from erlport.erlterms import Atom
from scipy.optimize import basinhopping
import numpy as np
import qsim
class Bounds(object):
'''Required for acceptance testing in scipy.optimize.basinhopping'''
def __init__(self, xmin, xmax, costs):
self.xmax = xmax
self.xmin = xmin
self.costs = costs... |
5,574 | aa801bc8398cdf69a15d04188dd8429e4624150e | import numpy as np
#read data from file
#read data from file
theFile = open('datapri.txt','r')
temp = []
#n la so phan tu cua mang mau
n = int(theFile.readline().format())
for val in theFile.read().split():
temp.append(int(val))
theFile.close()
arr = np.random.rand(n,n)
k = 0
for i in range(n):
for j in range... |
5,575 | 1284de6474e460f0d95f5c76d066b948bce59228 | #!usr/bin/env python3
from argoverse.map_representation.map_api import ArgoverseMap
from frame import Frame
import matplotlib.pyplot as plt
import pickle
import numpy as np
from argo import draw_local_map
# Frames in cluster visualization
def frame_in_pattern_vis(xmin, xmax, ymin, ymax):
dataset = 'ARGO'
if ... |
5,576 | 1b49cb59ebdb548cfc7567cd5cb4affe30f33aac | import pytest
@pytest.mark.usefixtures("driver")
class BaseClass:
"""BaseClass takes in driver fixture."""
|
5,577 | bc7a7b9ba4b3277c862aadb57b56661c24efc6e5 | from django.db import models
# Create your models here.
class Orders(models.Model):
customer_name = models.CharField(max_length=80)
customer_email = models.CharField(max_length=120)
customer_mobile = models.CharField(max_length=40)
status = models.CharField(max_length=20)
process_url = models.Cha... |
5,578 | 9e37b728d8045726aef7625fccc14111ecb0e1c8 | # -*- coding: utf-8 -*-
# @Author: Lich_Amnesia
# @Email: alwaysxiaop@gmail.com
# @Date: 2016-11-17 11:00:33
# @Last Modified time: 2016-11-17 11:00:34
# @FileName: 346.py
class MovingAverage(object):
def __init__(self, size):
"""
Initialize your data structure here.
:type size: int
... |
5,579 | 888a5847beca2470f4063da474da1f05079abca9 | from django.test import TestCase, Client
from django.urls import reverse
from django.contrib.auth import get_user_model
from tweets.models import Tweet
from ..models import UserProfile
User = get_user_model()
class TestAccountsViews(TestCase):
def setUp(self):
self.username = 'masterbdx'
self.ema... |
5,580 | 67e06b6dddbd3f26295eaff921d1ad4a8b0e5487 | import importlib
class Scrapper:
def get_pos(str_lf,str_rg,text):
left = text.find(str_lf)
right = text.rfind(str_rg)
return left, right
def scrapper(prov):
scrapper = importlib.import_module('scrappers.{}'.format(prov))
return scrapper.scrape()
|
5,581 | fa825846c54ed32c2ede94128ac08f9d5e172c0f | # -*- coding: utf-8 -*-
import urllib2, json, traceback
from django.conf import settings
from django.db import models
from TkManager.order.models import User
from TkManager.juxinli.models import *
from TkManager.juxinli.error_no import *
from TkManager.common.tk_log import TkLog
from datetime import datetime
from djan... |
5,582 | a372289d15b55f43887a37bb78a9fc308ddd0371 | # Generated by Django 3.0.4 on 2020-03-24 16:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('students', '0002_auto_20200324_1635'),
]
operations = [
migrations.AddField(
model_name='student',
name='parent_mobi... |
5,583 | 9da6bfa614d64956a302abbfeeea30c0339e9db3 | import tensorflow.contrib.slim as slim
import tensorflow as tf
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import init_ops
import numpy as np
WEIGHT_DECAY = 0.0005
class ScaledVarianceUniform(init_ops.Initializer):
"""Initializer that genera... |
5,584 | e364a4e6e1c4e0fd6805515a1149adaf92e9c8fb | n = input()
n = list(n)
n.sort()
alph = []
num = []
for i in range(n) :
if i.isalpha() :
alpa.append(i)
else :
num.append(i)
result.append(str(alpa))
result.append(str(num))
print(n)
|
5,585 | 8a6c9fa67c02d69444c9c3a2e6811b982c49eb4e | """Contains functionality for tokenizing, parsing, embedding language."""
from . import parsing
from . import cleaning
from .config import NATURAL_EMB_DIM
|
5,586 | 5068336ca1a180e09a7efd41eea596cdcebb33ae | from flask import Blueprint, request, jsonify
from to_dict import *
from validacao import *
import sqlite3
from migration import conectar, create_database
from contextlib import closing
aluno = Blueprint("aluno", __name__)
@aluno.route("/hello")
def hello():
return "Hello, aluno"
@aluno.route("/reseta", methods ... |
5,587 | 4bc9896847e4ab92a01dfcf674362140cc31ef4f | import ga.ga as ga
import os
import datetime
def ga_optimise(synth, param_count, target, output_dir, iterations = 10, pop_size = 500):
fs = ga.ga_optimise(compute_population_fitnesses = ga.compute_population_fitnesses,
target = target,
synth = synth,
param_count = param_count,
iterations = iterat... |
5,588 | a352768c2928cb7a33b9f1a31a0b3d8e56a8376a | # -*- coding: utf-8 -*-
# Scrapy settings for reddit_scraper project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'reddit_scraper'
SPIDER_MODULES = ['reddit_s... |
5,589 | 012ab947f7a2c9d44f54464b3e477582ffcf3d77 | # -*- coding: utf-8 -*-
"""
current_models - library of ionic current models implemented in Python
Created on Mon Apr 10 16:30:04 2017
@author: Oliver Britton
"""
import os
import sys
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
" Voltage clamp generator function... |
5,590 | c005ae9dc8b50e24d72dbc99329bb5585d617081 | from rest_framework.serializers import ModelSerializer
from rest_framework.serializers import ReadOnlyField
from rest_framework.serializers import SlugField
from rest_framework.validators import UniqueValidator
from django.db import models
from illumidesk.teams.util import get_next_unique_team_slug
from illumidesk.us... |
5,591 | ebd510bcd0caded03c5bcc36a11945710d5e644b | # -*- coding: utf-8 -*-
from datetime import datetime, timedelta
import math
import re
import copy
from lcs import lcs
# Create your models here.
keywords=["int","long","for","while","if","else","break","continue","return","true","false","double","do","signed","unsigned"]
symbol=["[","]","{","}","(",")","&","|","^",... |
5,592 | 6e2fb9d498294a580426ff408183f7beec135329 | # function to add two numbers
def add2nums(a,b):
return a+b
|
5,593 | 1bd1769f94b93e0bb674adfd1bb96c778708f6d8 | from django.urls import re_path
from .consumers import ChatConsumer, ChatLobbyConsumer
websocket_urlpatterns = [
re_path(r'ws/chat/(?P<room_id>\w+)/$', ChatConsumer),
re_path(r'ws/lobby/$', ChatLobbyConsumer),
] |
5,594 | cfba55505f3290a14b98d594bc871a74812c7c57 | """
Note: names of methods in this module, if seem weird, are the same as in Hunspell's ``suggest.cxx``
to keep track of them.
"""
from typing import Iterator, Union, List, Set
from spylls.hunspell.data import aff
MAX_CHAR_DISTANCE = 4
def replchars(word: str, reptable: List[aff.RepPattern]) -> Iterator[Union[str... |
5,595 | 53841ba56589955e09b03018af1d0ae79b3756c4 | #!/usr/bin/python
# coding=utf-8
import time
import atexit
# for signal handling
import signal
import sys
# ----------------------
# Encoder stuff
# ----------------------
import RPi.GPIO as GPIO
# init
GPIO.setmode(GPIO.BCM) # use the GPIO names, _not_ the pin numbers on the board
# Raspberry Pi pin configuratio... |
5,596 | b739c1de6c008158ee3806bed9fa2865eb484b4f | import sys
sys.stdin = open("sample_input_17.txt","r")
T = int(input())
def code(N): # 암호코드가 있는 열의 위치를 찾음
code = []
for i in range(N-4):
for j in range(49,53):
if S[i][j] == "1" :
code = S[i]
return code
def code_s(code): # 암호코드의 행 위치를 찾아 슬라이싱
for x in ... |
5,597 | 430dccf1001af43c2a713b08dc05d8f04818aa1f | #Script to retrieve relevant files and paths, supply to cx_Freeze to compile into executeable
import os
# import cx_Freeze
files_list = []
dir_path = os.path.dirname(os.path.realpath(__file__))+str('/')
print(dir_path)
for root, directories, filenames in os.walk(str(dir_path)):
for file in filenames:
pat... |
5,598 | f6f0dcb806fbc1e14c0907dd500fdc6a609a19f7 | # -*- encoding: utf-8 -*-
"""
Created by eniocc at 11/10/2020
"""
import ctypes
from py_dss_interface.models.Base import Base
class MonitorsS(Base):
"""
This interface can be used to read/write certain properties of the active DSS object.
The structure of the interface is as follows:
CStr Monit... |
5,599 | 85a3682f144f02aa412d45c901f76c65de2e816d | import graphics
from graphics import *
class Renderer():
def __init__(self, engine, width=700, height=600):
self.width = width
self.height = height
self.engine = engine
self.win = GraphWin("Game Board", width, height)
self.win.setBackground("blue")
def update(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.