index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
7,300 | 1305991a9cd82ddeaffff1545a35ced992e6792f | ####################################################################################
#
# Kaggle Competition: https://www.kaggle.com/c/msk-redefining-cancer-treatment
# Sponsor : Memorial Sloan Kettering Cancer Center (MSKCC)
# Author: Amrut Shintre
#
#####################################################################... |
7,301 | aec374ffa368755350d0d75c96860f760e8524e1 | from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from .models import Post
from django.shortcuts import redirect
from django.core.exceptions import ObjectDoesNotExist
def index(request):
blogs = Post.objects.filter(status=... |
7,302 | e8ef3a5e41e68b4d219aa1403be392c51cc010e6 | """
对自定义的类进行排序
"""
import operator
class User:
def __init__(self, name, id):
self.name = name
self.id = id
def __repr__(self):
return 'User({},{})'.format(self.name, self.id)
def run():
users = [User('wang', 1), User('zhao', 4), User('chen', 3), User('wang', 2)]
# 这种方式相对速度快... |
7,303 | 562888201719456ed2f3c32e81ffd7d2c39dabc3 | # Generated by Django 3.1.2 on 2020-10-25 01:19
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='job',
name='link',
... |
7,304 | 01e9ceb516a323a2017c65e368da419c6570dce2 | # -* coding: utf-8 -*-
# A headless media player based on gstreamer.
from gi.repository import Gst
Gst.init(None)
class Player:
def __init__(self, uri=None):
# Creates a playbin (plays media from an uri).
self.player = Gst.ElementFactory.make('playbin', 'player')
self.uri = uri
@pro... |
7,305 | b6ee3c980357ab22a7969c21207b34546c87092d | from .exec_generator import * |
7,306 | bb64da929ff2e1e04267518ec93a28bedb5a4de5 | # ---------------------MODULE 1 notes--------------------
# .
# .
# .
# .
# .
# .
# .
# .
# .
# .
# save as (file).py first if not it will not work
print("Hello")
# control s to save
|
7,307 | 0cf90cd7704db9f7467e458b402fadb01c701148 | from search import SearchEngine
import tkinter as tk
if __name__ == "__main__":
ghettoGoogle = SearchEngine()
def searchButtonEvent():
search_query = searchQueryWidget.get()
search_results = ghettoGoogle.search(search_query)
resultsCanvas = tk.Tk()
if search_results == None: ... |
7,308 | 282dbdb3a8d9ed914e8ca5c7fa74d2873920e18c | def area (a, b):
resultado = a * b
return (resultado)
def main():
#escribe tu código abajo de esta línea
num1 = float(input("INTRODUCE LA BASE: "))
num2 = float(input("INTRODUCE LA ALTURA: "))
print ("EL AREA DEL RECTANGULO ES: ", area (num1, num2))
pass
if __name__ == '__main__':
main()
|
7,309 | f311b803d8c0ee68bc43526f56e6b14f3a2836b8 | #### As an example below shell script can be used to execute this every 300s.
####!/bin/bash
####while true
####do
#### /usr/bin/sudo python3 /path/of/the/python/script.sh
####done
#!/usr/bin/python
import sys
import time
import paho.mqtt.client as mqtt
broker_url = "<IP_Address_of_MQTT_broker>"
b... |
7,310 | b5568e84e19719f0fd72197ead47bd050e09f55d | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# groupby()
# groupby()把迭代器中相邻的重复元素挑出来放在一起:
import itertools
for key, group in itertools.groupby('ABAABBBCCAAA'):
print(key, list(group))
# 小结
# itertools模块提供的全部是处理迭代功能的函数,它们的返回值不是list,而是Iterator,只有用for循环迭代的时候才真正计算。
|
7,311 | 54d6121898dc027d6ecaf9c9e7c25391778e0d21 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# sockdemo.py
#
# test
import struct, threading, signal
a = ''
if not a:
print 'a'
else:
print 'b'
import datetime, time, os
print datetime.datetime.now().strftime('%m-%d %H:%M:%S')
def double(x): return x*x
arr = [1, 2, 3, 4, 5]
print map(double, arr)
print 2**16
... |
7,312 | 5f84c8654c976bca2fa33e8f9ba5e28e3249253d | import numpy as np
import faiss
from util import vecs_io, vecs_util
from time import time
import os
'''
提取vecs, 输出numpy文件
'''
def vecs2numpy(fname, new_file_name, file_type, file_len=None):
if file_type == 'bvecs':
vectors, dim = vecs_io.bvecs_read_mmap(fname)
elif file_type == 'ivecs':... |
7,313 | 8340872f03c1bf7c1aee0c437258ac8e44e08bb8 | # 5.2 Training a convnet from scratch on a "small dataset" (p.131)
# Preprocessing (p.133)
# Copying images to train, validation and test directories
import os, shutil
# The path to the directory where the original dataset was uncompressed
original_dataset_dir = 'E:/train/'
# The directory where we will store our sma... |
7,314 | 800d87a879987c47f1a66b729932279fc8d4fa38 | #Homework 2 PyPoll
#The total number of votes cast
#A complete list of candidates who received votes
#The percentage of votes each candidate won
#The total number of votes each candidate won
#The winner of the election based on popular vote.
#First we'll import the os module
# This will allow us to create file pat... |
7,315 | 3ef114dd35ef3995ae73bf85bbe38db4fb7045d8 |
#from __future__ import absolute_import
#import os
from celery import Celery
#from django.conf import settings
#os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learning.settings')
app = Celery('tasks', broker="redis://localhost")
#app.config_from_object('django.conf:settings')
#app.autodiscover_tasks(lambda: setti... |
7,316 | 7c80c98e32f386362003ac3cd729fa9b279b8e8e | import numpy as np
import cv2
import serial
import serial.tools.list_ports
import time
import random
import math
#import mcpi.minecraft as minecraft
#import mcpi.block as block
#from house import House
#Arduino Serials
ports = list(serial.tools.list_ports.comports())
print (ports)
for p in ports:
print (p[1])
... |
7,317 | 50e759ff24cdb8fbb5a98d9381afb13ebc1a74f1 | import json
from bottle import request, response, route, get, run, default_app
app = application = default_app()
@route('/candidate/hired', method=['POST'])
def update_delete_handler():
response.content_type = 'application/json'
return json.dumps({"hired": True})
def main():
run(host='localhost', port... |
7,318 | ad84a5bfcf82dff1f4a7e8f08f3c4243ad24de52 | from foods.fruits import *
orange.eat()
apple.eat()
|
7,319 | 2867a7b24b4911b2936cb34653fa57431c14d6a3 | #Displaying multiple images using matplotlib
import pandas as pd
import numpy as np
import cv2
import matplotlib.pyplot as plt
def main():
imgpath1="C:\Shreyas\OpenCv\DIP_OpenCV\lena.png"
imgpath2="C:\Shreyas\OpenCv\DIP_OpenCV\lena.png"
img1=cv2.imread(imgpath1,1)
img2=cv2.imread(imgpath2,... |
7,320 | 8142585827590f6d951f0fcc375e8511aa75e9c8 | # from https://github.com/tensorflow/models/tree/master/research/object_detection/dataset_tools
# and https://gist.github.com/saghiralfasly/ee642af0616461145a9a82d7317fb1d6
import tensorflow as tf
from object_detection.utils import dataset_util
import os
import io
import hashlib
import xml.etree.ElementTree as ET
imp... |
7,321 | 1c5cb9363c2903905f1026ede77615e8373c250b | from django.db import models
# Create your models here.
class Login(models.Model):
trinity_id = models.CharField('',max_length=200)
trinity_password = models.CharField('',max_length=500)
objects = models.Manager() |
7,322 | c91be6cc332139c5b1e7ee5a3512482d0f8620b1 |
def selectionSort(arr, low, high):
for i in range(len(arr)):
mini = i
for j in range(i + 1, len(arr)):
if arr[mini] > arr[j]:
mini = j
arr[i], arr[mini] = arr[mini], arr[i]
return arr
|
7,323 | 58667da8898c2277ecc3d9d738d6553dd3416436 | ############################################-############################################
################################ F I L E A U T H O R S ################################
# MIKE - see contacts in _doc_PACKAGE_DESCRIPTION
####################################### A B O U T #######################################... |
7,324 | 1ebf92cf40053e561b04a666eb1dd36f54999e2c |
if __name__ == '__main__':
import sys
import os.path
srcpath = sys.argv[1] if len(sys.argv) >= 1 else './'
verfn = sys.argv[2] if len(sys.argv) >= 2 else None
try :
with open(os.path.join(srcpath,'.svn/entries'),'r') as fp:
x = fp.read().s... |
7,325 | 3f1715763a066fb337b3ff3d03e3736d0fb36b3f | from PyQt5 import QtCore
from PyQt5.QtWidgets import QTableWidgetItem, QDialog
from QT_view.PassportAdd import PassportAddDialog
from QT_view.PassportWin import Ui_Dialog
from Repository.Rep_Passport import PassportRepository
class PassportQt(QDialog):
def __init__(self):
super(PassportQt, self... |
7,326 | 5af5c10c149c7b0e2a969be7895780d26a4294d0 | import csv
with open('faculty.csv') as facultycsv:
emails = list() #all email addresses
for line in facultycsv:
line = line.split(',')
if line[0] == 'name' : continue
try:
email = line[3].rstrip()
emails.append(email)
except:
continue
with o... |
7,327 | 956adc5961188458393b56564649ad0a3a787669 | x = 5
y = x
print(id(x))
print(id(y))
print()
y = 3
print(id(x))
print(id(y))
print()
z = [1, 4, 3, 25]
w = z
print(z)
print(w)
print(id(z))
print(id(w))
print()
w[1] = 10
print(z)
print(w)
print(id(z))
print(id(w))
# So when you assign a mutable, you're actually assigning a reference to the mutable,
# and I... |
7,328 | af5ebdcd818fdf9c607240733b7b5dbb793cf55e | # put your python code here
a = int(input())
b = int(input())
# and
i = 1
if a == b:
print(a)
else:
while True:
if i // a > 0 and i % a == 0 and i // b > 0 and i % b == 0:
print(i)
break
else:
i += 1
|
7,329 | 3b9193fcd69b0387222feab96c50bf3617606cdd | from typing import List, cast
import numpy as np
from ..dataset import Transition
from .base import TransitionIterator
class RandomIterator(TransitionIterator):
_n_steps_per_epoch: int
def __init__(
self,
transitions: List[Transition],
n_steps_per_epoch: int,
batch_size: in... |
7,330 | 5c4a48de94cf5bfe67e6a74c33a317fa1da8d2fa | from django.db import models
from django.urls import reverse
from django.conf import settings
from embed_video.fields import EmbedVideoField
from django.contrib.auth.models import AbstractBaseUser
User = settings.AUTH_USER_MODEL
# Create your models here.
"""class User(models.Model):
username = models.CharField(... |
7,331 | 86345702bcd423bc31e29b1d28aa9c438629297d | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 18 16:11:44 2021
@author: ignacio
"""
import matplotlib.pyplot as plt
from numpy.linalg import inv as invertir
from time import perf_counter
import numpy as np
def matriz_laplaciana(N, t=np.single): # funcion obtenida de clase
e=np.eye(N)-np.eye(N,N,... |
7,332 | 84a63f60a45f1f8fc1efec8f30345a43c3c30c63 | def html_print(text, title=''):
from IPython.core.display import display, HTML
# create title for the content
display(HTML("<h4>" + str(title) + "</h4>"))
# create content
html = display(HTML("<font size=2 face=Verdana>" + text + "</font>"))
return html
|
7,333 | aafadcbf946db8ed85e3df48f5411967ec35c318 | #!/usr/bin/env python
# ----------------------------------------------------------
# RJGlass Main Program version 0.2 8/1/07
# ----------------------------------------------------------
# Copyright 2007 Michael LaBrie
#
# This file is part of RJGlass.
#
# RJGlass is free software; you can redistribute it and/or ... |
7,334 | 4843239a41fe1ecff6c8c3a97aceef76a3785647 | import operator
def group_by_owners(files):
print(files, type(files))
for k, v in files.items():
# for v in k:
print(k, v)
# if k[v] == k[v]:
# print("same", v)
for f in files:
print(f[0])
for g in v:
print(g)
_files = sorted(files.items(... |
7,335 | 5a13c7e3be8a0b5f3baf7106a938fc97f078c5bc | '''
Created on May 17, 2016
@author: Shauryadeep Chaudhuri
'''
import json
import tornado
from engine import Constants as c
from engine.ResultGenerator import ResultGenerator
from ..ServerLogger import ServerLogger
class GetFromURL(tornado.web.RequestHandler):
'''
This class fetches the d... |
7,336 | eb1fbe2de3c8548175eb3c8720353e466e3b68c7 | import rdflib
import csv
from time import sleep
gtypes = {}
dtypes = {}
atypes = {}
g = rdflib.Graph()
g.parse("http://geographicknowledge.de/vocab/CoreConceptData.rdf#")
g.parse("./ontology.ttl", format="ttl")
sleep(.5)
results = g.query("""
prefix skos: <http://www.w3.org/2004/02/skos/core#>
prefix ccd: ... |
7,337 | 47d72379b894826dad335f098649702ade195f78 | n=int(input("Digite um número"))
m=n-1
o=n+1
print("Seu número é {} seu antecessor é {} e seu sucessor é {}".format(n,m,o)) |
7,338 | a72d878d246a459038640bf9c1deff562994b345 | def solution(skill, skill_trees):
answer = 0
for tree in skill_trees:
able = True
for i in range(len(skill) - 1, 0, -1):
index = tree.find(skill[i])
if index != -1 and i > 0:
if tree[:index].find(skill[i - 1]) == -1:
able = False
... |
7,339 | 42d26ef51bb4dafc8a0201a828652e166a3905e4 | def unique(lisst):
setlisst = set(lisst)
return len(setlisst)
print(unique({4,5,1,1,3})) |
7,340 | 8e443d136a4e9fcdd18a106192f9c097928b8c99 | from typing import List, Any, Callable, Iterable, TypeVar, Tuple
T = TypeVar('T')
def partition(pred: Callable[[T], bool], it: Iterable[T]) \
-> Tuple[List[T], List[T]]: ...
|
7,341 | 62dab85b7ab5fdae8117827b2f56bccf99615cb7 | a=[[*map(int,input().split())]for _ in range(int(input()))]
a.sort()
s=0
l0,h0=a[0]
for l,h in a:
if h0<h:s+=(l-l0)*h0;l0,h0=l,h
l1,h1=a[-1]
for l,h in a[::-1]:
if h>h1:s+=(l1-l)*h1;l1,h1=l,h
s+=(l1-l0+1)*h1
print(s) |
7,342 | 8bb86cae3387a0d4ce5987f3e3c458c8298174e0 | from .settings import *
# Heroku Configurations
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES = {'default': dj_database_url.config()}
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# loading local_se... |
7,343 | db231ea92319414dd10ca8dfbc14e5a70ed2fe44 |
from QnA_processor.question_analysis.google_question_classifier import GoogleQuestionClassifier
def classify_question(query):
try:
"""
Get answer-type from google autoML classifier
(by making POST requests with authorization key)
"""
question_c... |
7,344 | f704742b9e023a1c3386fed293032fd8196b875e | # -*- coding: utf-8 -*-
# Author : Seungyeon Jo
# e-mail : syjo@seculayer.co.kr
# Powered by Seculayer © 2018 AI-Core Team
from mlps.core.data.cnvrtr.ConvertAbstract import ConvertAbstract
class Substr(ConvertAbstract):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def apply(self,... |
7,345 | 12fd4e3bfb6821205a9b65b4d236b4158ec4ef1e | #!/usr/bin/env python
#
# Copyright 2017-2021 University Of Southern California
#
# 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... |
7,346 | 357ee02060cbfa391920b3d45dfbe16e679a6c8d | def spam(divide_by):
return 42 / divide_by
try:
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
print(spam("dog"))
except Exception:
print("Error: Invalid argument.")
|
7,347 | 4473971552aa48236b19dec7e7c1ea1e622d5795 | from subprocess import check_output
import json
import sys
import time
import os
import numpy as np
from hutch_python.utils import safe_load
from ophyd import EpicsSignalRO
from ophyd import EpicsSignal
from bluesky import RunEngine
from bluesky.plans import scan
from bluesky.plans import list_scan
from bluesky.plan_... |
7,348 | e247ffb5b6e4319ff17d0b8ae9f67e10c282c4ff |
# 多角色认证装饰器
def auth(role):
from core import admin_view,student_view,teacher_view
def deco(func):
def wrapper(*args,**kwargs):
if role == 'admin':
if admin_view.admin_user == None:
admin_view.login()
else:
res = func(... |
7,349 | 8c96c38a67c2eb97e30b325e4917ba4888731118 | import json
import boto3
import os
import datetime
regionName = os.environ['AWS_REGION']
BUCKET_PATH = os.environ['BUCKET_PATH']
SENSITIVIT = os.environ['SENSITIVIT']
s3_client = boto3.client('s3', region_name=regionName)
ddb_resource = boto3.resource('dynamodb', region_name=regionName)
def lambda_handler(event, co... |
7,350 | f9cee552dde5ecf229fda559122b4b0e780c3b88 | class Solution:
def countLetters(self, S: str) -> int:
ans = 0
for _, g in itertools.groupby(S):
cnt = len(list(g))
ans += (1 + cnt) * cnt // 2
return ans
|
7,351 | e1751cc6f76f56e62cd02d61db65f1c27a4ff1b9 | #encoding=utf-8
import pytest
from frame_project.实战2.main_page import MainPage
class TestMian:
def test_mian(self):
MainPage().goto_marketpage().goto_search().search()
if __name__ == '__main__':
pytest.main(['test_case.py','-s','-v'])
|
7,352 | 1b091d139635e90fb53b3fecc09bb879514c7b38 | import os
import json
from google.appengine.ext import webapp
from generic import JsonRpcService
class ViewService(JsonRpcService):
def json_create(self):
return "Hello, World!"
|
7,353 | 3cf2ffbc8163c2a447016c93ff4dd13e410fff2b | # -*- coding: utf-8 -*-
class Task:
def __init__(self):
self.title = ''
self.subtasks = []
def set_title(self, title):
self.title = title
def set_subtasks(self, subtasks):
self.subtasks = subtasks
|
7,354 | 98dbc6c3bdc3efb4310a2dbb7b1cc1c89eb4582b | import urllib3
with open('python.jpg', 'rb') as f:
data = f.read()
http = urllib3.PoolManager()
r = http.request('POST', 'http://httpbin.org/post', body=data, headers={'Content-Type': 'image/jpeg'})
print(r.data.decode()) |
7,355 | a9b1cc9b928b8999450b6c95656b863c476b273b | import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMainWindow, QApplication
#---Import that will load the UI file---#
from PyQt5.uic import loadUi
import detechRs_rc #---THIS IMPORT WILL DISPLAY THE IMAGES STORED IN THE QRC FILE AND _rc.py FILE--#
#--CLASS CREATED THAT WILL LOAD THE UI FILE... |
7,356 | bb3c42c9f87a463b9f18601c9e3897b6d21351d5 | from django.db import models
from django.utils import timezone
from django.db.models.signals import post_save
from django.urls import reverse
# Create your models here.
class Purchase(models.Model):
invoice = models.SmallIntegerField(primary_key=True,blank=False)
ch_no = models.SmallIntegerField(blank=True,nul... |
7,357 | 3328c2ae0816c146398ecde92a056d1e77683696 | import tkinter as tk
from telnetConn import telnetConnection
fields = 'Host Address', 'UserName', 'Password', 'Message To', 'Text'
def fetch(entries):
input_list = []
for entry in entries:
field = entry[0]
text = entry[1].get()
input_list.append(text)
# print('%s:... |
7,358 | ff8b6bc607dac889da05b9f7e9b3595151153614 | import requests
import json
from concurrent import futures
from tqdm import trange
def main():
ex=futures.ThreadPoolExecutor(max_workers=50)
for i in trange(1,152):
url="https://api.bilibili.com/pgc/season/index/result?season_version=-1&" \
"area=-1&is_finish=-1©right=-1&season... |
7,359 | 2305d0b7ec0d9e08e3f1c0cedaafa6ed60786e50 | #! /usr/bin/env python3
import common, os, shutil, sys
def main():
os.chdir(common.root)
shutil.rmtree('shared/target', ignore_errors = True)
shutil.rmtree('platform/build', ignore_errors = True)
shutil.rmtree('platform/target', ignore_errors = True)
shutil.rmtree('tests/target', ignore_errors = True)
shut... |
7,360 | cf5ab10ce743aa261867501e93f498022e5908fe | #!python3
import configparser
parser = configparser.ConfigParser()
parser.read("sim.conf")
print(parser.get("config", "option1"))
print(parser.get("config", "option2"))
print(parser.get("config", "option3"))
|
7,361 | e47d6b5d46f2dd84569a2341178b2ea5e074603a | import cv2
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import SeparableConv2D, Conv2D, MaxPooling2D
from keras.layers import BatchNormalization, Activation, Dropo... |
7,362 | bcc2977f36ecc775f44ae4251ce230af9abf63ba | '''
This module demonstrates how to use some functionality of python built-in csv module
'''
import csv
def csv_usage():
'''
This function demonstrates how to use csv module to read and write csv files
'''
with open('example.csv', 'r', newline='') as csvfile:
reader_c = csv.reader(csvfile, deli... |
7,363 | 5066c2a5219cf1b233b4985efc7a4eb494b784ca | def gen_metadata(fn):
metadata = {}
lines = open(fn,'r').readlines()
for line in lines:
line = line.rstrip()
if len(line) == 0:
continue
elif line.startswith('#'):
continue
elif line.startswith('%'):
continue
else:
# Special case RingThresh
firstWord = line.split()[0]
if line.startswith('... |
7,364 | 0d8a26ef4077b40e8255d5bb2ce9217b51118780 | #!/usr/bin/python3
# encoding: utf-8
"""
@author: ShuoChang
@license: (C) MIT.
@contact: changshuo@bupt.edu.cn
@software: CRNN_STN_SEQ
@file: decoder_base.py
@time: 2019/7/22 17:21
@blog: https://www.zhihu.com/people/chang-shuo-59/activities
"""
from abc import ABCMeta
from abc import abstractmethod
class DecoderBas... |
7,365 | c2dba981b0d628aebdf8cebfb890aad74a629b08 | from enum import Enum
from app.utilities.data import Prefab
class Tags(Enum):
FLOW_CONTROL = 'Flow Control'
MUSIC_SOUND = 'Music/Sound'
PORTRAIT = 'Portrait'
BG_FG = 'Background/Foreground'
DIALOGUE_TEXT = 'Dialogue/Text'
CURSOR_CAMERA = 'Cursor/Camera'
LEVEL_VARS = 'Level-wide Unlocks and ... |
7,366 | 4745d81558130440d35d277b586572f5d3f85c06 | import unittest
import userinput
class Testing(unittest.TestCase):
def test_creation(self):
x = userinput.UserInput()
self.assertNotEqual(x, None)
def test_charset_initialization(self):
x = userinput.UserInput()
self.assertEqual(x.character_set, userinput.CHARACTERS)
def ... |
7,367 | e14b8d0f85042ceda955022bee08b3b3b4c2361d | # Generated by Django 3.0.8 on 2021-03-25 13:47
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Asha', '0005_baby'),
]
operations = [
migrations.AlterField(
model_name='baby',
... |
7,368 | a0460b100a750b685f3e831a19379b0e26da4b35 | # x = 10
#
# def increment():
# x += 1
#
# ^^ Non-working code
x = 10
def increment(number):
number += 1
return number
# If we want to change a global variable,
# we have to do it like this
x = increment(x) |
7,369 | 72b5e76f63e347d7275b0b711fa02b7f327785f6 | #!/usr/bin/python
import os
import sys
fdatadir = "/fdata/hepx/store/user/taohuang/NANOAOD/"
datasets = []; NumSample = []; sampleN_short = []
Nanodatasets = []; localdirs = {}
MCxsections = []
#doTT=True; doDY=True; doVV=True; doSingleT=True; doWjets=True; dottV=True
##DoubleEG
datasets.append('/DoubleEG/Run2016B-0... |
7,370 | 975b2f3443e19f910c71f872484350aef9f09dd2 | class Solution:
def minimumDeviation(self, nums: List[int]) -> int:
hq, left, right, res = [], inf, 0, inf
for num in nums:
if num % 2:
num = num * 2
heapq.heappush(hq, -num)
left = min(left, num)
while True:
right = -heapq.heap... |
7,371 | 452d5d98b6c0b82a1f4ec18f29d9710a8c0f4dc9 | """
This handy script will download all wallpapears from simpledesktops.com
Requirements
============
BeautifulSoup - http://www.crummy.com/software/BeautifulSoup/
Python-Requests - http://docs.python-requests.org/en/latest/index.html
Usage
=====
cd /path/to/the/script/
python simpledesktops.py
"""
from StringIO imp... |
7,372 | 7c3569c43d27ba605c0dba420690e18d7f849965 | from django import forms
from .models import User,Profile
from django.contrib.auth.forms import UserCreationForm
class ProfileForm(forms.ModelForm):
''' Form for the profile '''
class Meta:
model = Profile
exclude = ('user',) ## we will create the user with the signals
class SignUpForm(Use... |
7,373 | 4dfdbc692858a627248cbe47d19b43c2a27ec70e | #!/usr/bin/env python
# Core Library modules
import os
# Third party modules
import nose
# First party modules
import lumixmaptool.copy as copy
# Tests
def get_parser_test():
"""Check if the evaluation model returns a parser object."""
copy.get_parser()
def parse_mapdata_test():
current_folder = os.p... |
7,374 | f15bb4ab93ecb2689bf74687852e60dfa98caea9 | """Project agnostic helper functions that could be migrated to and external lib.
"""
|
7,375 | 0259fddbe3ce030030a508ce7118a6a03930aa51 | from flask import Flask
import os
app = Flask(__name__)
@app.route("/healthz")
def healthz():
return "ok"
@app.route("/alive")
def alive():
return "ok"
@app.route("/hello")
# def healthz(): # introduces application crash bug
def hello():
myhost = os.uname()[1]
body = ("V1 - Hello World! - %s" % m... |
7,376 | 5c643dfce9cf7a9f774957ff4819d3be8ac4f1da | #list,for replacing element we use {a[0='']}:for adding element we use {append()}
a=['somesh','aakash','sarika','datta','rudra','4mridula']
a[2] = 'nandini'
a.append('sarika')
print(a[2])
print(a)
|
7,377 | 7a920b3609bb29cd26b159b48290fa6978839416 | def bullets(chunks):
print("bullets")
final_string = "Your list in latex can be created with the following command: \n"
final_string += "> \\begin{itemize} \n"
for e in chunks:
print(final_string)
final_string += f"> \item {e} \n"
final_string += "> \end{itemize}"
retur... |
7,378 | f8e287abc7e1a2af005aa93c25d95ce770e29bf9 | from odoo import models, fields, api
from datetime import datetime, timedelta
from odoo import exceptions
import logging
import math
_logger = logging.getLogger(__name__)
class BillOfLading(models.Model):
_name = 'freight.bol'
_description = 'Bill Of Lading'
_order = 'date_of_issue desc, writ... |
7,379 | 92d689e5caa2d8c65f86af0f8b49b009d162a783 | from turtle import *
from shapes import *
#1-
#1.triangle
def eTriangle():
forward(100)
right(120)
forward(100)
right(120)
forward(100)
right(120)
mainloop()
#2.square
def square():
forward(100)
right(90)
forward(100)
right(90)
forward(100)
right(90)
forwa... |
7,380 | e4f194c3dbc3e1d62866343642e41fa1ecdeab93 | #!/usr/bin/python3
import os, re
import csv, unittest
from langtag import langtag
from sldr.iana import Iana
langtagjson = os.path.join(os.path.dirname(__file__), '..', 'pub', 'langtags.json')
bannedchars = list(range(33, 45)) + [47] + list(range(58, 63)) + [94, 96]
def nonascii(s):
cs = [ord(x) for x in s]
i... |
7,381 | 6b3cb7a42c8bc665e35206b135f6aefea3439758 | """ DB models.
"""
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from db.session import map_engine, replay_engine
MapBase = declarative_base(bind=map_engine)
ReplayBase = declarative_base(bind=replay... |
7,382 | c6ab82d7f59faeee2a74e90a96c2348b046d0889 | #Multiple Word Palindromes
#Ex 72 extended
word = input("Word: ")
new = []
o = []
r = []
#canceling out the spaces
for i in range(len(word)):
if word[i] in ".,?!" or word[i] == ' ':
pass
else:
new.append(word[i])
#original
for i in range(len(new)):
o.append(new[i])
#reverse
for i in range(... |
7,383 | cdabb4a118cb0ef55c271a446fa190a457ebe142 | #!/usr/bin/env python
# -*- coding:utf-8 _*-
"""
:Author :weijinlong
:Time: :2020/1/10 17:22
:File :graph.py
:content:
"""
import tensorflow as tf
from .base import TFLayer
class TFModel(TFLayer):
def build_model(self):
raise NotImplementedError
def add_outputs(self, *a... |
7,384 | 401c6b09edf593e00aecf5bbb1b2201effc9e78c | #
# @lc app=leetcode id=14 lang=python3
#
# [14] Longest Common Prefix
#
# @lc code=start
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
pass
# At the moment I just wanna test my workspace so it's working tomorrow it's time for the problems
# @lc code=end
|
7,385 | 1dd09a09f542099091d94d466ebd7cc149884eb4 | import time
from junk.keyboard_non_blocking import NonBlockingKeyboard
TICK_DURATION = 0.05
INITIAL_FOOD_LEVEL = 100
FOOD_PER_TICK = -1
FOOD_PER_FEED = 10
MAX_FOOD_LEVEL = 100
INITIAL_ENERGY_LEVEL = 50
ENERGY_PER_TICK_AWAKE = -1
ENERGY_PER_TICK_ASLEEP = 5
MAX_ENERGY_LEVEL = 100
INITIAL_IS_AWAKE = False
INITIAL_PO... |
7,386 | 70188d011ef60b1586864c4b85a9f9e70e5a4caf | from fastapi import FastAPI, Header, Cookie, Form, Request, requests, Body, Response, HTTPException, status, Path, Query
from fastapi.responses import HTMLResponse
from typing import Optional
from fastapi.testclient import TestClient
from typing import List, Callable
from fastapi.staticfiles import StaticFiles
from fas... |
7,387 | 2d20bac0f11fa724b2d0a2e0676e5b9ce7682777 | # -*- coding: utf-8 -*-
# Copyright (c) 2018-2019 Linh Pham
# wwdtm_panelistvspanelist is relased under the terms of the Apache License 2.0
"""WWDTM Panelist Appearance Report Generator"""
import argparse
from collections import OrderedDict
from datetime import datetime
import json
import os
import shutil
from typing ... |
7,388 | 5172819da135600d0764033a85a4175098274806 | import numpy as np
import pandas as pd
import datetime
import time
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors import KNeighborsRegressor
from sklearn.model_selection import cross_val_score
from sklearn import preprocessing
from sklearn.model... |
7,389 | ec0113dbd79e936e614bb7ee7e48d29aa616d511 | num=int(input())
i=10
while i>=1:
print(i,end=" ")
i-=1
|
7,390 | e9a1fd8464f6c1e65aa2c1af60becbfcbf050814 | import tensorflow as tf
import numpy as np
import tensorflow.contrib.layers as layers
class Model(object):
def __init__(self, batch_size=128, learning_rate=0.01, num_labels=10, keep_prob=0.5, scope="model"):
self._batch_size = batch_size
self._learning_rate = learning_rate
self._num_labels ... |
7,391 | 34a456efc72b303aed5f722bb415d30ff62addab | import numpy as np
import argparse
import torch
from gridworlds.envs import GridWorldEnv, generate_obs_dict
from gridworlds.constants import possible_objects
import nengo_spa as spa
from collections import OrderedDict
from spatial_semantic_pointers.utils import encode_point, ssp_to_loc, get_heatmap_vectors
import mat... |
7,392 | 1af9fb91e69ea78709c47fca6b12e4f7a6fd17a8 | import unittest
import os
import tempfile
import numpy as np
from keras_piecewise.backend import keras
from keras_piecewise import Piecewise2D
from .util import MaxPool2D
class TestPool2D(unittest.TestCase):
@staticmethod
def _build_model(input_shape, layer, row_num, col_num, pos_type=Piecewise2D.POS_TYPE_SE... |
7,393 | 096d82e1f9e8832f6605d23c8bb324e045b6b14f | ## Script (Python) "after_rigetta"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=state_change
##title=
##
doc = state_change.object
#Aggiornamento dello stato su plominoDocument
doc.updateStatus()
if script.run_script(doc, script.... |
7,394 | 303d56c18cce922ace45de1b8e195ebfdd874e23 | class product(object):
def __init__(self, item_name, price, weight, brand, status = "for sale"):
self.item_name = item_name
self.price = price
self.weight = weight
self.brand = brand
self.cost = price
self.status = status
self.displayInfo()
def displayInfo... |
7,395 | a538c6d8c9f99bc37def5817a54c831393c051f3 | #!/usr/bin/python
try:
fh = open('testfile','w')
try:
fh.write('This is my test file for this exception')
finally:
print "Going to close file"
fh.close()
except IOError:
print" Error: can\'t find file or read data"
|
7,396 | 582cbacd26f4a3ed0b4f5c85af67758de7c05836 | ### To run the test use:
### python3 -m unittest test_script.py
import unittest
import re
class TestCustomerDetails(unittest.TestCase):
def test_cu_name(self):
### Our script has a class ConfigurationParser, which will have method ParseCuNames
cp = ConfigurationParser()
### expected nam... |
7,397 | 0ebd3ca5fd29b0f2f2149dd162b37f39668f1c58 | from xgboost import XGBRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import pandas as pd
import numpy as np
from ghg import GHGPredictor
predictor = GHGPredictor()
dataset_df = pd.read_csv("db-wheat.csv", index_col=0)
# print(dataset_df.iloc[1])
dataset_d... |
7,398 | 7af19f69e6c419649a5999f594118ad13833a537 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 13 14:10:15 2018
9.5 项目:将一个文件夹备份到一个 ZIP 文件
@author: NEVERGUVEIP
"""
#! python3
import zipfile,os
def backupToZip(folder):
#backup the entire contents of 'folder' into a ZIP file
folder = os.path.abspath(folder)
os.chdir(folder)
#figure out the fil... |
7,399 | d39965c3070ec25230b4d6977ff949b3db070ab6 | """
Add requests application (adding and managing add-requests)
"""
from flask import Blueprint
__author__ = 'Xomak'
add_requests = Blueprint('addrequests', __name__, template_folder='templates', )
from . import routes |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.