index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
11,500 | dac16d8a11f95f8ec91a22d2fd9baca5d611a8a1 |
def solution(maze):
# 상우하좌
dr = (-1, 0, 1, 0)
dc = (0, 1, 0, -1)
N = len(maze)
r, c, d = 0, 0, 1
cnt = 0
while True:
if (r, c) == (N-1, N-1): # 목적지 도착
break
# 처음 왼쪽 안되면 시계방향 확인
d = (d + 3) % 4
for _ in range(4):
nr = r + dr[d]
... |
11,501 | 4af41560a916cd709a888dc108e2d92537007f1d | from django.shortcuts import render, redirect, HttpResponse
from django.views.generic import View
from .forms import *
from django.contrib.auth import login, authenticate, logout as dj_logout
from .models import *
from app.models import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
f... |
11,502 | 59028563e4bc3e698179dceb0bf67190cda6643a | # Generated by Django 2.2.5 on 2020-02-21 12:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0007_auto_20200220_0729'),
]
operations = [
migrations.AddField(
model_name='product',
name='slug',
... |
11,503 | 682d6e0d9866afe5defb3c0fec8a78ef0167d044 | # -*- coding: utf-8 -*-
n = int(input())
horas = n // 3600
n %= 3600
minutos = n // 60
n %= 60
print('{0:d}:{1:d}:{2:d}'.format(horas, minutos, n))
|
11,504 | 1bd356d2666da63fca9e62178c37e9b03d006dd5 | import sys,os
import math
from optparse import OptionParser
# define options
parser = OptionParser()
parser.add_option("-t", "--tower", dest="tower", default=28, help="tower number")
parser.add_option("-b", "--border", dest="border", default=0, help="tower border (0 = center, -1 = low eta, 1 = high eta")
parse... |
11,505 | a57b641b0771c551351ce4984848775f30be467a | from flask import render_template, request, Blueprint, flash, redirect, url_for, make_response, current_app
from src.models import SignIn, User
from src import db
from src.users.forms import SignInForm, ContactForm
from src.services import business_url_return, EmailService, create_cookie, grab_cookie
from src.users.dec... |
11,506 | 47b81fa78bf88e0eadf627e0c92a848715af73d1 | # Generated by Django 2.2.4 on 2019-08-18 14:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('foods', '0010_auto_20190818_1434'),
]
operations = [
migrations.AlterField(
model_name='recipeingredient',
name='qua... |
11,507 | 93d23f282427712ec4f662f9686bb46ed44f71df | from models.simulation.Simulate import simulate_money_line
from models.atp_tennis.TennisMatchMoneyLineSklearnModels import bet_func
import pandas as pd
if __name__ == '__main__':
# test edge cases
prob_pos = [0.6, 0.6, 0.6, 0.6, 0.6, 0.6]
actual = [1, 1, 0, 1, 0, 1]
parameters = {
'max_loss_pe... |
11,508 | 558e62159759c15224a0a404ce157b7f2910afad | ###
## Reads a pattern csv file and returns the most common grid passwords
##
## D.E. Budzitowski 150876
###
import sys,csv,collections,Image
def main(argv):
## Error Check
if len(argv) is not 1 or (int(argv[0]) is not 3 and int(argv[0]) is not 4):
exit("incorrect args")
## Path to file... |
11,509 | e962aeb4ba59e49a30b07812de5ac36392d763c1 | #!/usr/bin/python3
import random
from typing import List
from player import Player
from games import snake, hangman, skribble
class Main(object):
def __init__(self):
self.players: List = []
self.games = [
skribble.Skribble(),
hangman.Hangman(),
snake.Snake()
... |
11,510 | 71c186fbe3a9784352f856c4b92a5c333d25f946 | from util import input_rows
def largest_value(instructions):
largest_ever = 0
for name in register_names(instructions):
locals()[name] = 0
for instruction in instructions:
exec(translate(instruction))
largest_ever = max(largest_ever, _largest_int(locals().values()))
locals_copy... |
11,511 | 7dc822da0f55722da70ecd1b2b6432f9cd99ab6b | import json
with open('persons.json', 'r') as f:
my_dict = json.load(f)
for distro in my_dict:
print(distro['gender'])
print(distro['name'])
|
11,512 | 91a4c0453cc58b567892c1daac6dc9efec9b5b3a | #---------------------------------------------------------------------------
# Twitter Streaming Bot - Copyright 2017, Leo Brack, All rights reserved.
#---------------------------------------------------------------------------
# This code tracks keyword mentions by streaming real time data from the
# the twitter API.... |
11,513 | b76de5a900151a387b058faca063cbca48730196 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1358/B
Solution: Carefully observing the question, we can see that we don't need to summon the grannies
in batches, rather can do them all at once as long as their constraint of enough grannies present
in the courtyard is satisfied. This would... |
11,514 | 77f1fce7a8ff9511df3eea6d50c43e42feb9d218 | """
Example of a map-reduce type operation where a list of A_i is mapped to a list of B_i
and then reduced to produce C.
The B_i are stored in intermediate values, and we wish to delete them after C has been computed.
In this example we use check_valid="shallow" so the deletion of B_i does not cause the
re-computation... |
11,515 | 4b3066c508bd43cb2dae68cc6ed1aec83486a959 | # Create your views here.
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect
from django.views import generic
from .forms import SignUpForm
from .models import Blog, PostComment, Post
def index(request):
"""
View function for home page of site.
"""
# R... |
11,516 | 67395c63422ca82a8608100ef201ea05207429f2 | import os, sys
import warnings
warnings.filterwarnings("ignore")
import tensorflow as tf
sys.path.append('/'.join(os.path.abspath(__file__).split('/')))
from ornstein_auto_encoder import logging_daily
from ornstein_auto_encoder import configuration
from ornstein_auto_encoder.utils import argv_parse
from ornstein_auto_... |
11,517 | a4334c7ae30f58379fe0da5c3ce3cecf164de0af | """All the logic for commands does in this class"""
import os
import unittest
from server_file import Server
class Tester(unittest.TestCase):
"""This class test with given inputs to perform unittest.
Methods
-----------
test_create_folder(self):
tests the given input with user input and checks ... |
11,518 | 7af1be3b636addb839c864850db3909023296c40 | from mbuild import recipes
import mbuild as mb
from foyer import Forcefield
import sys
sys.path.append('../../../../../../')
from mosdef_slitpore.utils import charmm_writer as mf_charmm
Water_res_name = 'H2O'
Fake_water_res_name = 'h2o'
FF_file = '../../../../../../mosdef_slitpore/ffxml/pore-spce.xml'
FF_file_fake_... |
11,519 | c9011a4b75b0e39da3986e34ca61bcc593afcd7a | def birthdayCakeCandles(ar):
ar.sort()
max=ar[len(ar)-1]
x=0
for i in ar:
if i==max:
x=x+1
print(x)
ar_count = int(input())
ar = list(map(int, input().rstrip().split(' ')))
birthdayCakeCandles(ar) |
11,520 | fc872b19018d6d27309d18c19dd572035830598f | import markus
print('start main')
markus.main() |
11,521 | ddae115e5fd2f0c0938ab5cd41761b35c6980bfd | '''
Init
'''
from .default import *
|
11,522 | cce84b3ad27139883cc6497ff5e097d5c679572c | # Generated by Django 2.2.11 on 2020-03-16 15:57
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Shellies',
fields=[
('id', models.AutoFiel... |
11,523 | 14865dd8b054aea769794d6fd72b9fe26903baf9 | default_app_config = 'course_admin.apps.CourseadminConfig' |
11,524 | ed5e6a388ebff262652a074404fee33e80aec1f8 | from .models import (
User, UserProfile,
Education,
WorkExperience,
Specialization,
SecurityQuestion,
Answer,
KeyVal,
EmployeeBasicDetails,
EmployeeProfessionalDetails,
EmployeeEmploymentDetails,
EmployeeWorkDetails,
EmployeeAvailability,
Resume,
BankAccounts,
... |
11,525 | 7b687abbea16666eb55bad160c0c202b1d34d5ca | from django.db import models
from django.contrib.auth.models import AbstractUser
from mainapp.models import Template1
class User(AbstractUser):
USER_ROLE = (
('inspector', 'Инспектор'),
('office', 'Офис'),
('client', 'Клиент'),
)
phone = models.CharField('Телефон', max_length=50, bl... |
11,526 | 8422ecc52832ebaea63752e530110ad9b6f66d5a | # script1.py
from script2 import y, z
def x(i):
if i % 2:
z(i)
return y(i)
return z(i)
if __name__ == "__main__":
for i in range(3):
x(i)
z(i)
|
11,527 | 4432b06769b3715c8465bdf25e125285f3698b7f | import haystack
from haystack.signals import RealtimeSignalProcessor
from django.db.models import signals
from ..utils import check_solr
_old_sp = None
def setup():
check_solr()
global _old_sp
_old_sp = haystack.signal_processor
haystack.signal_processor = RealtimeSignalProcessor(haystack.connections... |
11,528 | 6902836d40ef174415fc595845bad9e0914b6354 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2020/8/7 上午11:18
# @Author : 尹新
# @Site :
# @File : config
# @Software: PyCharm
from happy_python import HappyConfigBase
class Config(HappyConfigBase):
"""
配置文件模板
"""
def __init__(self):
super().__init__()
self.section = 'main... |
11,529 | f0913bc638f3088aad834b4902aaa1410d2a9e39 | from django.template.response import TemplateResponse
from .forms import AppForm
def apps_review(request):
print("apps_review")
pass
def app_review(request):
print("app_review")
pass
def create_app(request):
app_form = AppForm(request.POST or None)
if app_form.is_valid():
app_form... |
11,530 | 855e6477ff1a9c48f47ab3e345d06801b1c93395 | from typing import List
from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from . import crud, models, schemas
from .database impo... |
11,531 | efa7ec6bc992aa3147da51ab3f63002a623a88a5 | #!/root/ysy/python/bin/python3
'''myerror
trigger error
'''
def age_fun1(name,age):
if not 1 < age < 120:
raise ValueError("age out of range")
print("%s is %s years old"%(name,age))
def age_fun2(name,age):
assert 1 < age < 120,"age out of range too"
print("%s is %s years old" % (name, age))
i... |
11,532 | 65969a74b27cf13f02dec3b82bdedd96a02c5231 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: model/detection/protos/losses.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf impor... |
11,533 | dd7e6073edcac533193552e9520349bc59146e98 | from Organisms.Animals.Animal import Animal
import random
class Fox(Animal):
def draw(self):
return "#ff5000"
def __init__(self, tile, world):
super().__init__(tile, world)
self.strength = 3
self.initiative = 7
def action(self):
moves = self.world.get_neighbours(... |
11,534 | 7b3a6c55aad3be9f559f323c254cf51f21dd0b81 | import os
import csv
import matplotlib.pyplot as plt
import pandas as pd
path = "./result"
file_list = os.listdir(path)
instance_list = []
scheduler_list = []
for i in file_list:
if i.find("instance") != -1:
instance_list.append(i)
else:
scheduler_list.append(i)
results = []
for... |
11,535 | e51e0757c3190eb0d89ed2b0ba68710ae7730b9b | from heapq import heappush, heappop
n, e = map(int, input().split())
INF = int(1e9)
data = [[] for _ in range(n + 1)]
for _ in range(e):
a, b, c = map(int, input().split())
data[a].append((c, b))
data[b].append((c, a))
def dijkstra(start, end):
distance = [INF for _ in range(n + 1)]
distance[s... |
11,536 | 5f6f8ff9aad6a51cd05ed5d9b0e9043ab9663ebe | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
##############################################################################
"""Perform inference on a single image or al... |
11,537 | 9168a7a6b95e50d0b2da5ef4d9307c337f1f8f0b | from ea_adult_selection import adult_select_pareto_crowding_distance
from ea_genetic_operators import displacement_mutation, ordered_crossover, hill_climbing
from ea_genome import TSPGenome
from ea_parent_selection import parent_select_crowding_tournament
class InvalidDatasetError(Exception):
pass
class TSPProb... |
11,538 | baca6e9ba078d33d59bba3f726e9dd99727c9374 | import sys
sys.path.append('../../../')
import keras
from keras.layers import Input, Dense, Activation
from keras.layers.merge import Maximum, Concatenate
from keras.models import Model
from keras.optimizers import Adam
from keras.utils import plot_model
# import required to load the attacked model
from autoencoder_BA... |
11,539 | 486943180fbbf03e94e4458c00e083297db6dc47 | import unittest
import os
from itertools import combinations_with_replacement
from query import search, levenshtein
from index import Trie, DEFAULT_FILENAME
WORDS_FILENAME = '/tmp/words'
WORDS_CONTENT = "aa ab bb bc c".replace(' ', "\n")
WORDS = WORDS_CONTENT.split()
class TestIndex(unittest.TestCase):
def test... |
11,540 | 7e5496a802278837a12a6a9e812287135f464468 | from contextlib import contextmanager
from uuid import uuid4
import pandas as pd
from google.cloud import bigquery
from .basic import Profiler
class SqlProfiler(Profiler):
def __init__(self, project, sql, *args, **kwargs):
super().__init__(project, sql)
self.client = bigquery.Client(project=proj... |
11,541 | f9971ef3370082d5dca2f679c5146184ab74b815 | import pandas as pd
a = int(-9999)
df=pd.read_csv("/home/marcela/Downloads/RECOMMENDATIONFIX/recommendations_cleanup/test_9999.csv", quotechar='"');
print(df['multi_graph_id'])
df['multi_graph_id']=df['multi_graph_id'].fillna("-9999")
df['recommended_width']=df['recommended_width'].fillna("-9999")
print(df['multi... |
11,542 | a2aa040caf30dc642da3c241e4478470dfa4e756 | def alphabet_position(letter):
alphabet = "abcdefghijklmnopqrstuvwxyz"
return alphabet.index(letter.lower())
def rotate_character(char, rot):
alphabet = "abcdefghijklmnopqrstuvwxyz"
if char.isalpha():
idx = (alphabet_position(char) + rot) % 26
if char.islower():
return alph... |
11,543 | 71758a8fb7f01126817975a201df7138fcfab5ba | def index(src, search):
try:
if (src.index(search) >= 0 ):
return src.index(search);
except ValueError as ve:
return -1; |
11,544 | 74be04192aa747f2fcd81b73f8d74903fcf86d57 | from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.views.generic.base import TemplateView
from homepage.views import HomePageView
from profiles.views import ProfileRedirectView
admin.autodiscover()
handler404 = 'homepage.views.error_404_v... |
11,545 | e15dc6d20c691a643fb184992e45bb6d3f55aac1 | class car:
def __init__(self, speed, color, name, is_police):
self.name = name
self.speed = speed
self.color = color
self.is_police = is_police
print(f"New {self.color} {self.name} is born!")
def go(self):
print(f"{self.color} car {self.name} is going")
def... |
11,546 | b2ec682fba5d5eec999d160d44c829f93d8caa36 | # -*- coding: utf-8 -*-
# @Time : 2018/4/9 14:53:17
# @Author : SilverMaple
# @Site : https://github.com/SilverMaple
# @File : routes.py
import hashlib
import os
import logging
import sys
import shutil
import json
import subprocess
import time
from datetime import datetime
from app.decorators import async
f... |
11,547 | 232a94c70a60cb665a437533b846325d66557d1a | # -*- coding:utf-8 -*-
#!flask/bin/python
import sys
import os
if sys.platform == 'wn32':
pybabel = 'flask\\Scripts\\pybabel'
else:
pybabel = 'flask/bin/pybabel'
os.system(pybabel + ' compile -d app/translations') |
11,548 | 6d2f1f18ba935ef53365076252e9bcb63ebf0b6c | import math
from thread import Thread
from drivers import MPU6050, HTS221
from machine import Pin, I2C
from connection import MessagingService, Wifi, MqttConnection, BudgetManager, config
import ubinascii
import machine
import utime
import ujson
import sys
TOPIC_DEVICE_PACKAGE = 'hcklI67o/device/{}/package'
TOPIC_TE... |
11,549 | 53c13809873ddd7b81636dbcaef3fac390c6f1c9 | #!/usr/bin/env python
"""
point_density.py
Calculate density of point data as a raster surface.
Each raster cell contains a value indicating
the number of points contained in the cell.
To get decent performance on large vector datasets, the input vector dataset must
have a gdal-recognized spatial index (ie a .q... |
11,550 | 34c4433ad4b7bff9670e11ee1c312c3184082960 | import random
import turtle
class Maze(object):
"""docstring for Maze"""
class Cell(object):
"""docstring for Cell"""
def __init__(self):
self.edges = []
self.visited = False
def link(self, neighbor):
newedge = Maze.Edge(self, neighbor)
self.edges.append(newedge)
neighbor.edges.append(newedge)... |
11,551 | 700befadf7deb736d5f5e1267effc464de38e0ba | # Copyright 2020 Google LLC
# 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 or agreed to in... |
11,552 | e7454e475aa1ebebbd3ea344c2157cedb4fe3373 | #!/usr/bin/env python
# coding=utf-8
from __future__ import print_function
import unittest
import os
import tempfile
from mock import Mock, patch
from click.testing import CliRunner
from shub import deploy_reqs
@patch('shub.deploy_reqs.utils.build_and_deploy_egg')
class TestDeployReqs(unittest.TestCase):
VALID... |
11,553 | 19aff83506523dcaf850040fbd055c1d49162931 | from flask import Flask,views,jsonify,request,make_response,json,g,redirect,abort,g,current_app
from ..models import Comment,Post,Tag,Email,AppUser as User,PublicUser
from itsdangerous import TimedJSONWebSignatureSerializer as signer
from ..app_factory import get_app
from ..cache import set_cache,get_cache,make_secret_... |
11,554 | 13b87794d1426239ac22f3c5eb8fb12641e81a16 | __author__ = "Zhijie Huang"
import time
def f(a):
if a % 2 == 0:
return a // 2
else:
return 3 * a + 1
def count(b, k):
steps = [-1 for i in range(b+1)]
steps[1] = 0
for i in range(2, b):
if steps[i] == -1:
path = []
l = i
for j in rang... |
11,555 | 85ab6a97e44d247b3cca4663dcd9d02b256b333f | from fabric.context_managers import cd
from fabric.api import run, put, env
from cloudify import ctx
#env.use_ssh_config = True
def wf_deploy(wf_url, wf_name):
ctx.logger.info('workflow download ' + wf_url)
run('mkdir RawaWF')
run('git clone --recursive ' + wf_url + ' RawaWF/' + wf_name)
with cd('Rawa... |
11,556 | cfac6a17bb3bde9434753394e21819819a53474e | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
from luther_app.views import index, overview, preface, intro, text, images, works, page, xml, send_file
urlpatterns = patterns('luther_app.views',
url(r'^$', 'index', name='i... |
11,557 | 863a109c4c960601938e24aec6fc7fb4f988f0d4 | import pygame
import math
pygame.init()
win_height = 480
win_width = 500
win = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption('First Game')
x = 50
y = 400
width = 64
height = 64
vel = 5
run = True
is_jump = False
jump_count = 10
left = False
right = False
walk_count = 0
walk_right = [... |
11,558 | bd26b141ca88847a2f31b3889d9bc93d68f4c84b | from datetime import timedelta, datetime
#from datetime import datetime
from decimal import Decimal
from pprint import pprint
from django.conf import settings
from django.core.mail import send_mail
from celery.task import task
from celery.task import periodic_task
from celery.task.schedules import crontab
from dbtra... |
11,559 | ff4378460279731b297b93c221701bb4534f1326 | import requests
r = requests.get('http://knit.ac.in/')
print (r.status_code)
print (r.headers)
print (r.encoding) |
11,560 | a412b2bb3ddffb5c9ebf2a84737fb29c9279af3d | #estaciones "IOPV"
import os
palabra=os.sys.argv[1]
for estacion in palabra:
if(estacion=="V"):
print("Verano")
if(estacion=="P"):
print("Primavera")
if(estacion=="O"):
print("Otoño")
if(estacion=="I"):
print("Invierno")
#fin bucle
|
11,561 | a58fa9c0c2ee0917ae92f713516a04f3fef01d53 | import boto3
import paramiko
class spin_and_execute:
def __init__(self):
self.ssh_output = None
self.ssh_error = None
self.client = None
#self.host= conf_file.HOST
#self.username = conf_file.USERNAME
#self.password = conf_file.PASSWORD
#self.timeout = flo... |
11,562 | bf996f0b467466e26e2f496d8dd6f0b5302dddc4 | import json
from unittest.mock import MagicMock, Mock
from uuid import uuid4
import pytest
from django.contrib.auth.models import AnonymousUser
from django.core import signing
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from django.urls import reverse
from django_babel.te... |
11,563 | 7e9234597455aeaa1b0bdff7d179cd04b4d2194e | #!/usr/bin/env python
# coding=utf-8
import urllib3
import re
from db.db_mongo import add_fund_info, fund_set_count, update_fund_info
pool = urllib3.PoolManager()
# 初始化基金信息
def init_fund_infos():
data_re = re.compile(r'=.\[(.*?)\];$')
item_re = re.compile(r'\[(\".*?\")\]')
# today = datetime.datetime.n... |
11,564 | 5add37663126aa7290c17d8891b753ef567001cf | from django.db import models
class Pais(models.Model):
nombre = models.CharField(max_length=30)
class Ciudad(models.Model):
nombre = models.CharField(verbose_name='Nombre de la ciudad', max_length=30)
pais = models.ForeignKey(Pais, on_delete=models.CASCADE)
poblacion = models.PositiveIntegerField()
|
11,565 | c92ca95b3219be78baede0f75f701e476a406da2 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from quilt3distribute import FeatureDefinition
from quilt3distribute.validation import Validator, validate
@pytest.mark.parametrize("dtype, validation_functions", [
(str, []),
(str, (... |
11,566 | a26d1381f1a923c023ab6f7961fed15892a6caca | from datetime import datetime
def voto(nascimento):
global ano
idade = ano - nascimento
if idade < 16:
return f'Com {idade} anos, sua situação de voto é: PROIBIDO'
elif idade >= 18 and idade <= 65:
return f'Com {idade} anos, sua situação de voto é: OBRIGATÓRIO'
else:
return... |
11,567 | 44cd4f4945e71c456af52153f53adcf3194e171a | def codechef(n,a,b,c,floor):
#cook your dish here
diff_lis = []
time = abs(b-a)+c
if a>=b:
x1 = a
x2 = b
elif b>a:
x1 = b
x2 = a
for i in floor:
if x2<i<x1:
return time
for i in range(len(floor)):
if floor[i]>=x1:
... |
11,568 | 1565b7521cb4cef6eeb7a48094398f3eee8e7f10 | from .base import *
from .logging import *
DEBUG = True
SERVER_EMAIL = "Wikilink Local <wikilink.local@localhost.localdomain>"
DEFAULT_FROM_EMAIL = SERVER_EMAIL
# Django Debug Toolbar config
# ------------------------------------------------------------------------------
# Sometimes, developers do not want the deb... |
11,569 | 6ce1c576b8b297e7d17d786a45424c797e6142ee | #!/usr/bin/env python3
import json
import sys
if len(sys.argv) != 2:
print(f"usage {__file__} <annotation file>")
sys.exit(1)
with open(sys.argv[1], "r") as f:
j = json.load(f)
topmodule = j["top_module"]
cnt = 0
for i, (modulename, annots) in enumerate(j["modules"].items()):
inline... |
11,570 | 92375817b72e8e982169748cab1af709331e6f01 | # coding: utf-8
# Author:南岛鹋
# Blog: www.ndmiao.cn
# Date :2021/2/27 21:09
# Tool :PyCharm
import sys
import pymysql
import time
import json
import traceback #追踪异常
import requests
def get_conn():
"""
:return: 连接,游标
"""
# 创建连接
conn = pymysql.connect(host="127.0.0.1",
us... |
11,571 | 9440eff5ce7ed1fac9948a21808977d0bb848372 | from django.shortcuts import render
from django.contrib import messages
# Create your views here.
def home(request):
import requests
import json
api_request = requests.get("https://newsapi.org/v2/everything?sources=techradar&apiKey=96cc98dbabea497b921dcd946f249e78")
api = json.loads(api_request.content... |
11,572 | adfca1376e8dfed3f51c57ce5e7fb1ac32ec4b1a | import pandas as pd
import numpy as np
import requests
import json
from langdetect import detect
import nltk
from nltk.tokenize import sent_tokenize
nltk.download('punkt')
df = pd.read_csv('noNAN4Body.csv',encoding = "utf-8", low_memory=False)
methodName = 'doInBackground'
includedLines = []
includedbo... |
11,573 | b16e0e2e849a0899158c6b8649ef182748fb0d6e | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Импортируем библиотеку pygame
import pygame
from pygame import *
#Объявляем переменные
WIN_WIDTH = 800 # Ширина создаваемого окна
WIN_HEIGHT = 640 # Высота
DISPLAY = (WIN_WIDTH, WIN_HEIGHT) # Группируем ширину и высоту в одну переменную
BACKGROUND_COLOR = "#004400"
###... |
11,574 | 06f976d1797edf572aaa5aba0d755f95c56b3c26 | from typing import Sequence
import pandas as pd
from pandas.api import types as pdt
from visions.relations import IdentityRelation, TypeRelation
from visions.types.type import VisionsBaseType
def _get_relations(cls) -> Sequence[TypeRelation]:
from visions.types import Object
relations = [IdentityRelation(c... |
11,575 | 72afe244f76a37fa80b24b49fcc8617d3656b5d2 | # Copyright (c) 2020-2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# 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 ... |
11,576 | d5f737bf11f27e2bf5bfc21b3498d66f9db38312 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 29 23:23:50 2020
@author: swedkm
"""
import geopandas as gpd
import pandas as pd
import os
from multiprocessing import Pool
def clean_sales_shp(county):
#create a directory for each county folder and set the path
directory = 'C:\Anaconda3\MN_Scra... |
11,577 | f822f162f7dfa3e7f68dbdd3e0065bb40c5720c1 | import os
import shutil
from pathlib import Path
from flask import request, send_from_directory
from flask_restplus import Resource
from bson import ObjectId
from app.main.util.decorator import token_required
from app.main.model.database import *
from task_runner.runner import start_threads
from ..service.auth_helper... |
11,578 | b91610f9854aa02da932597040fb30ba6d180963 | from presentation import elem, elem2, factorial, factorial2, _map, _map2, quicksort
# elem
assert elem(1, [1,2]) == True
assert elem(3, [1,2]) == False
assert elem(4, [1,2]) == False
assert elem(4, [4]) == True
assert elem(1, []) == False
# elem2
assert elem2(1, [1,2]) == True
assert elem2(4, [4]) == True
assert ele... |
11,579 | 7a5bfbe81cb5c3b5aaab479131174970f3db906d |
{
'name': 'Task Log: limit Task by Project',
'version': '12.0.1.0.0',
'category': 'Human Resources',
'website': 'http://www.planet-odoo.com',
'author':
'Planet-odoo',
'installable': True,
'application': False,
'summary': (
'Limit task selection to tasks on currently-sele... |
11,580 | 508788436016b28ebd6842700dcdc9ed87739fe0 | import json
import itertools
from compliance_checker.base import BaseCheck, BaseNCCheck, check_has, score_group, Result
from pkgutil import get_data
class ACDDBaseCheck(BaseCheck):
###############################################################################
#
# HIGHLY RECOMMENDED
#
###########... |
11,581 | 5bbb0a6ae6e09d81905dffb1ba683aab3d12312b | import sys
import numpy
import queue as Q
# build a priority queue for annotated peaks
def hashOrder(file):
RNA = {}
f = open(file)
while True:
line = f.readline()
if not line:
break
line = line.strip('\n').split("\t")
key = line[0]
# start and end postion
pair = (int(line[1]), int(line[2]))
... |
11,582 | dec288b980c0290aed712b0b63495ea79f3c4a7e | """
advancedSkeleton @ utils
"""
import maya.cmds as mc
import maya.mel as mm
def fixCtrlColors():
"""
Module to fix advanced skeleton auto rig controls colors to match the standard colors
:return: None
"""
#List all the controls in the scene to change color
controlsShapes = mc.ls( type = 'nu... |
11,583 | 667ab0cf5fdc5a746955eafad125cdbe23e9e025 | import logging, sys
from osdemo.core.kernel import Kernel
from osdemo.shell.commands import Commands
sys.path.append('lib/pyshell')
from pyshell.model.shell import Shell
from pyshell.gui.shellframe import ShellFrame
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s | %(message)s', level=logging.I... |
11,584 | 5ee65c0bacc76a7358aa4febf0c98573cc0ebcef | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QApplication
app = QApplication([])
clipboard = app.clipboard()
def on_clipboard_change():
data = clipboard.mimeData()
if data.hasFormat('text/uri-list'):
for path in data.urls(... |
11,585 | 530ff8c2f9439a213a126f074fdfaa0156727599 | from django.contrib import admin
from .models import Shop, Street, City
@admin.register(City)
class CityAdmin(admin.ModelAdmin):
pass
@admin.register(Street)
class StreetAdmin(admin.ModelAdmin):
list_display = ('name', 'city')
list_filter = ('city',)
@admin.register(Shop)
class ShopAdmin(admin.ModelAd... |
11,586 | d07c1020de2996021666f7a5c31a2ec9f59a8a50 | '''
File:
insteon_message.py
Description:
A set of classes for Insteon support.
Author(s):
Chris Van Orman
License:
This free software is licensed under the terms of the GNU public license, Version 1
Usage:
Example:
Notes:
Created on Mar 11, 2013
'''
from pytomation.interfaces.common import Comma... |
11,587 | 4478df320db5841fc9e4a6348d25c9bcfd755df2 | # https://leetcode.com/problems/ransom-note
from collections import Counter
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
r_cnt = Counter(ransomNote)
m_cnt = Counter(magazine)
for key in r_cnt:
if r_cnt[key] > m_cnt[key]:
retur... |
11,588 | 4048f88ccf12d026c1eefff7165927cfad372bef | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import click
import os
from . import utils
from . import om,r
from . import path
@click.group()
def tool():
pass
# package commands
@click.command()
def build():
"""Prepare packages and wheel locally"""
click.secho('Creating package ...')... |
11,589 | b536616a86d463a2043575230ae2618d661d1300 | import ctypes
import pathlib
libfile = ctypes.CDLL(
# relative to this module file
str(pathlib.Path(__file__).parent.absolute() / 'libcrashme.so')
)
c_crash_me = libfile.crash_me
c_crash_me.argtypes = []
def crash_me() -> None:
c_crash_me()
__all__ = [ 'crash_me' ]
|
11,590 | f9e80375b17cb3704b8ed808e9d91f47e84dfd78 | # Extract a shapefile from a gzipped tar archive
# https://github.com/GeospatialPython/Learning/raw/master/hancock.zip
import tarfile
tar = tarfile.open("hancock.tar.gz", "r:gz")
tar.extractall()
tar.close()
|
11,591 | af63447ebf21a36aed88a3069dddcdbe2b854da2 | from flask import Flask, jsonify, request
from hardwareController import *
from datetime import datetime
from apscheduler.schedulers.blocking import BlockingScheduler
import _thread
from apscheduler.schedulers.asyncio import AsyncIOScheduler
app = Flask(__name__)
feedevents = []
waterChangeLog = 'none'
@app.route("/... |
11,592 | 2ece032748d38e8efbf9c401919aa32c52069450 | import socket
HOST,PORT=('127.0.0.1',8080)
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((HOST,PORT))
while True:
s_data=input('==>:').strip()
if not s_data:continue
s.send(s_data.encode('utf-8'))
rec_data=s.recv(1024)
print(rec_data.decode('utf-8')) |
11,593 | 3b783857bd2ec30c6216f4edb7402a3ffca44b8e | '''
用 requests 库发起一个HEAD请求,并从响应中提取出一些HTTP头数据的字段
'''
import requests
resp = requests.head('http://www.python.org/index.html')
status = resp.status_code
last_modified = resp.headers['last-modified']
content_type = resp.headers['content-type']
content_length = resp.headers['content-length']
|
11,594 | 2b33e4d02bc4124bd808e94c7db9ed9ed935aeb2 | def CountVowelConstChar(S1):
count_v = 0
count_c = 0
count_ch = 0
i = 0
while i < len(S1):
if not S1[i].isalpha():
count_ch += 1
elif S1[i] == 'a' or S1[i] == 'e' or S1[i] == 'i' or S1[i] == 'o' or S1[i] == 'u':
count_v += 1
else:
... |
11,595 | 897c5e6d0b2b0818b221a6ac89f199807d547969 | class Configuration:
DEBUG=True
SQLALCHEMY_TRACK_MODIFICATIONS=False
SQLALCHEMY_DATABASE_URI='mysql+mysqlconnector://root:1111@localhost/database1'
SECRET_KEY='SECRET_KEY'
### flask security ###
SECURITY_PASSWORD_SALT='$2b$12$ctTq5EgEL6MyWooqQGwCe..cGsgCpyXVN08QartxThUNRJRD/PIai]'
SECURITY_... |
11,596 | 126261649978dce20cfca899323ec4ec68319d8a | from ShapeDescriptor import *
class VanishPencil:
def __init__(self, vanishRay=None):
self.vanishRays = None
if vanishRay:
self.vanishRays = [vanishRay] # List of vanishRays
def updateVanishRay(self, newVanishRay):
if self.vanishRays:
newWeight = newVanishRay.crossRatioVectorLength
oldWeight = self.va... |
11,597 | 75757d348fa4a7c564d510051894e451f090abc8 | __author__ = 'Chelsea | Michael'
import unittest
from Conect4_View import View
from unittest.mock import patch
from io import StringIO
class TestViewShowBoard(unittest.TestCase):
""" Checks the visual aspect of the game for the user interface """
def setUp(self):
"""Inits empty grid for testing"""
... |
11,598 | 100d1af34b3fd24243fa1d9d471b687ffa6120b0 | #! /usr/bin/env python
#For Python, this file uses encoding: utf-8
import sys
import numpy as np
import math as mat
from tabulate import tabulate
def esBroadcast(packet):
return packet.dst == "ff:ff:ff:ff:ff:ff"
def entropia( probaPorSimbolo ):
res = 0
for s,p in probaPorSimbolo.items():
res -= p * mat.log( p, ... |
11,599 | 17ed8e2e44467cb16afef5ab964897921f1afbcf | import pandas as pd
from geopy.geocoders import Yandex
import time,os.path
geolocator = Yandex( timeout=1) # proxies = proxies -
def formAddress(distr, street, house, korpus):
#print(distr, street)
oneAddr = str(distr) + ' район, ' + ' ' + str(street)
if house != '' and house != 'NaN':
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.