index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
6,700 | e81373c7b9c43b178f0f12382501be8899189660 | #
# Standard tests on the standard set of model outputs
#
import pybamm
import numpy as np
class StandardOutputTests(object):
"""Calls all the tests on the standard output variables."""
def __init__(self, model, parameter_values, disc, solution):
# Assign attributes
self.model = model
... |
6,701 | 54e5feee3c8bb35c351361fd3ed4b5e237e5973d | highscores = []
scores = []
while True:
user = input('> ').split(' ')
score = int(user[0])
name = user[1]
scores.append( [score, name] )
scores.sort(reverse=True)
if len(scores) < 3:
highscores = scores
else:
highscores = scores[:3]
print(highscores) |
6,702 | 533d0b883a0bbbb148f04826e4c0a2bcc31732e9 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
DIM Station Test
~~~~~~~~~~~~~~~~
Unit test for DIM Station
"""
import unittest
from dimp import ID, NetworkID
class StationTestCase(unittest.TestCase):
def test_identifier(self):
print('\n---------------- %s' % self)
str1 = 'gsp... |
6,703 | 0438f92aa9a36eaf1059244ec3be4397381f7a86 | import pyodbc
print("Primera consulta SQL Server")
servidor="LOCALHOST\SQLEXPRESS"
bbdd="HOSPITAL"
usuario="SA"
password="azure"
#CADENA CONEXION CON SEGURIDAD SQL SERVER (REMOTO)
cadenaconexion=("DRIVER={ODBC Driver 17 for SQL Server};SERVER=" + servidor
+ "; DATABASE=" + bbdd + "; UID=" + usuario + "; PWD=" + passw... |
6,704 | 82083f16c18db35193fa2aa45bc28c5201962f90 |
import re
match = re.search(r'pi+', 'piiig')
print 'found', match.group() == "piii"
|
6,705 | f73a3bd7665ac9cc90085fcac2530c93bef69d3d | # coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
from heapq import heappop, heappush
from collections import defaultdict
sys.setrecursionlimit(10**7)
import math
#from itertools import product#accumulate, combinations, product
#import bisect# lower_bound etc... |
6,706 | 808fe8f106eaff00cf0080edb1d8189455c4054b | import numpy as np
def find_saddle_points(A):
B = []
for i in range(A.shape[0]):
min_r = np.min(A[i])
ind_r = 0
max_c = 0
ind_c = 0
for j in range(A.shape[1]):
if (A[i][j] == min_r):
min_r = A[i][j]
ind_r = j
for k in range(A.shape[0]):
if (A[k][ind_r] >= max_c):
max_c = A[k][ind_... |
6,707 | 586d39556d2922a288a2bef3bcffbc6f9e3dc39d | import os
import random
import cv2
import numpy as np
from keras.preprocessing.image import img_to_array
import numpy as np
import keras
from scipy import ndimage, misc
def preprocess_image(img):
img = img.astype(np.uint8)
(channel_b, channel_g, channel_r) = cv2.split(img)
result = ndimage.maximum_filter(... |
6,708 | 7620d76afc65ceb3b478f0b05339ace1f1531f7d | def strictly_greater_than(value):
if value : # Change this line
return "Greater than 100"
elif value : # Change this line
return "Greater than 10"
else:
return "10 or less"
# Change the value 1 below to experiment with different values
print(strictly_greater_than(1))
|
6,709 | c95eaa09241428f725d4162e0e9f6ed3ce6f8fdd | # -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
from accounts.models import (UserProfile)
admin.site.register(UserProfile)
admin.site.unregister(User)
class CustomUserAdmin(UserAdmin):
list_display = ('username', ... |
6,710 | 9db4bca3e907d70d9696f98506efb6d6042b5723 |
from mcse.core.driver import BaseDriver_
class DimerGridSearch(BaseDriver_):
"""
Generates all dimer structures that should be considered for a grid search
to find the best dimer arangements. Grid search is performed over all
x,y,z positions for the COM and all orientations of the molecule. Only
... |
6,711 | f4094a81f90cafc9ae76b8cf902221cbdbc4871a | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'MainMenu.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWind... |
6,712 | bf05a096956ca4f256832e2fc6659d42c5611796 | # Generated by Django 3.1.2 on 2021-02-13 14:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('post', '0014_profilepic_user'),
]
operations = [
migrations.CreateModel(
name='profile_pic',
fields=[
... |
6,713 | b7721e95cfb509a7c0c6ccdffa3a8ca2c6bd6033 | from numpy import array, sum
def comp_point_ref(self, is_set=False):
"""Compute the point ref of the Surface
Parameters
----------
self : SurfLine
A SurfLine object
is_set: bool
True to update the point_ref property
Returns
-------
point_ref : complex
the refe... |
6,714 | 95ab8fce573ef959946d50d9af6e893cb8798917 | """Functions for updating and performing bulk inference using an Keras MPNN model"""
from typing import List, Dict, Tuple
import numpy as np
import tensorflow as tf
from molgym.mpnn.data import convert_nx_to_dict
from molgym.mpnn.layers import custom_objects
from molgym.utils.conversions import convert_smiles_to_nx
... |
6,715 | daf070291bbf59a7a06b129bbde5fd79b5cd46ad | '''
Created on Mar 19, 2019
@author: malte
'''
import gc
import pickle
from hyperopt import tpe, hp
from hyperopt.base import Trials
from hyperopt.fmin import fmin
from config.globals import BASE_PATH
from domain.features import FEATURES
from evaluate import evaluate
from featuregen.create_set import create_set
fro... |
6,716 | 515967656feea176e966de89207f043f9cc20c61 | """Config flow for Philips TV integration."""
from __future__ import annotations
from collections.abc import Mapping
import platform
from typing import Any
from haphilipsjs import ConnectionFailure, PairingFailure, PhilipsTV
import voluptuous as vol
from homeassistant import config_entries, core
from homeassistant.c... |
6,717 | 87c27711c0089ca2c7e5c7d0e9edb51b9d4008d9 | # -*- coding: utf-8 -*-
import requests
import csv
from lxml import html
import json
class ycombinatorParser():
siteurl = 'https://news.ycombinator.com/'
def getNextPage(pageurl):
response = requests.get(pageurl)
parsed_body = html.fromstring(response.text)
nextpage=parsed_body.xpa... |
6,718 | eb50f50e3c072c2f6e74ff9ef8c2fa2eef782aae | # Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
6,719 | d442d5c7afd32dd149bb47fc9c4355409c53dab8 | import array as arr
# from array import * # To remove use of 'arr' everytime.
studentMarks = arr.array('i', [2,30,45,50,90]) # i represnts datatype of array which is int here.
# accessing array
print(studentMarks[3])
studentMarks.append(95)
# using for loop
for i in studentMarks:
print(i)
# usin... |
6,720 | 8da775bd87bfeab5e30956e62bcdba6c04e26b27 | import json
# numbers=[2,3,5,7,11,13]
filename='numbers.json'
with open(filename) as f:
numbers=json.load(f)
print(numbers) |
6,721 | ea696329a0cfd558fb592ffaf6339a35e8950a3c | class Solution:
def commonFactors(self, a: int, b: int) -> int:
gcd = math.gcd(a, b)
return sum(a % i == 0 and b % i == 0
for i in range(1, gcd + 1))
|
6,722 | 4a4745f202275e45fd78c12431e355fd59ac964a | class SlackEvent:
@property
def client_msg_id(self):
pass
@property
def type(self):
pass
@property
def subtype(self):
pass
@property
def text(self):
pass
@property
def time_stamp(self):
pass
@property
def ... |
6,723 | d1b025ddbf7d0ad48ff92a098d074820a3eb35ed | #!/usr/bin/python
# encoding:utf-8
from selenium.webdriver.common.by import By
import random
import basePage
# 门店入库button
stock_in = (By.XPATH, "//android.widget.TextView[contains(@text,'门店入库')]")
# 调拨入库button
transfer_in = (By.XPATH, "//android.widget.TextView[contains(@text,'调拨入库')]")
# 确认签收button
take_receive = (By... |
6,724 | 7262d7a82834b38762616a30d4eac38078e4b616 | # 遍历(循环) 出字符串中的每一个元素
str01 = "大发放而非asdfasfasdfa,,,,aadfa阿斯顿发水电费&&"
# ----->字符串中的元素都是有索引的,根据索引可以得到对应的元素
# 而---3
a = str01[3]
print(str01[3])
# 发---1
print(str01[1])
#---->计算字符串的长度
# 这个字符串中 有 35个元素 ,长度是35
l01 = len(str01)
print(l01)
str01 = "大放而非asdfasfasdfa,,,,aadfa阿斯顿发水电费&&"
# 最后一个元素的索引:字符串... |
6,725 | 4af05a13264c249be69071447101d684ff97063e | import sys
import numpy as np
import math
import matplotlib.pyplot as plt
import random
def load_files(training, testing):
tr_feat = np.genfromtxt(training, usecols=range(256), delimiter=",")
tr_feat /= 255.0
tr_feat = np.insert(tr_feat, 0, 0, axis=1)
tr_exp = np.genfromtxt(training, usecols=range(-1)... |
6,726 | b49e5b40ce1e16f1b7c0bd9509daf94f36c51256 | from app.api import app
def main():
app.run(host='0.0.0.0', port=5001)
if __name__ == '__main__':
main()
|
6,727 | 4cc6a9c48e174b33ed93d7bda159fcc3a7b59d4c | from django.contrib import admin
from .models import Profile, Address
admin.site.register(Profile)
admin.site.register(Address)
|
6,728 | 5e78992df94cbbe441495b7d8fb80104ec000748 | #!/usr/bin/python2
import md5
from pwn import *
import time
LIMIT = 500
TARGET = "shell2017.picoctf.com"
PORT = 46290
FILE = "hash.txt"
def generate_hashes(seed):
a = []
current_hash = seed
for i in range(1000):
current_hash = md5.new(current_hash).hexdigest()
a.append(current_hash)... |
6,729 | 84a13e3dea885d6c4a5f195dfac51c7110102fc2 | #!/usr/bin/env python3
from ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3, INPUT_4
from ev3dev2.sensor.lego import ColorSensor, UltrasonicSensor
from ev3dev2.power import PowerSupply
# initiate color sensors
# the colour sensor needs to be between 1-2 cm away from the surface you are trying to measure. (color mode)
... |
6,730 | 787397473c431d2560bf8c488af58e976c1864d0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.17 on 2021-04-09 06:08
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lkft', '0021_reportjob_finished_successfully'),
]
operations = [
migration... |
6,731 | b39c783cbaff2915c8864ce0b081b5bf052baee5 | from django.urls import path
from .views import *
urlpatterns = [
path('country',Country_Data,name='country_data'),
path('tours',Scrape_Data, name='scrape_data'),
path('draws', Draw_Data, name='Draw_data')
]
|
6,732 | 4f21fb4168ed29b9540d3ca2b8cf6ef746c30831 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# http://stackoverflow.com/questions/5276967/python-in-xcode-4
"""tv_write_xyzt2matlab.py: TremVibe Write Accelerometer XYZ and Timestamp to .m file"""
__author__ = "Salvador Aguinaga"
import sys
import MySQLdb
import math
from itertools import groupby
import csv
##########... |
6,733 | db341c3686c53f1cd9fe98c532f17e872952cbba | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 15 17:28:48 2018
@author: otalabay
"""
LOCAL_INFO = 1
LSM = 2
TLS = 3
TLS_STOP = 4
DANGER = 5
STOP_DANGER = 6
PM = 7
PM_STOP = 8 |
6,734 | 56640454efce16e0c873d557ac130775a4a2ad8d | n,m=map(int,input().split())
l=list(map(int,input().split()))
t=0
result=[0 for i in range(0,n)]
result.insert(0,1)
while(t<m):
#print(t)
for i in range(l[t],n+1):
result[i]=result[i]+result[i-l[t]]
t=t+1
print(result[-1])
0 1 2 3 4
1 [1,1,1,1,1]
2 [1 1 2 2 3]
3 [... |
6,735 | 9f2105d188ac32a9eef31b21065e9bda13a02995 | # -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2015] Michał Szczygieł, M4GiK Software
#
# 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... |
6,736 | 34db3c9998e1d7647dd954e82e18147504cc74fc | """
@version:
author:yunnaidan
@time: 2019/07/22
@file: download_mseed.py
@function:
"""
from obspy.clients.fdsn import Client
from obspy.core import UTCDateTime
import numpy as np
import obspy
import os
import re
import time
import glob
import shutil
import platform
import subprocess
import multiprocessing
def load_... |
6,737 | 7da8a074704b1851ac352477ef72a4c11cea1a0b | #_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-#
# PROJECT : RegCEl - Registro para el Consumo Eléctrico #
# VERSION : 1.2 ... |
6,738 | 168a76fd3bb43afe26a6a217e90f48704b4f2042 | #!/usr/bin/env python3
import os
import requests
# This is the main url of the BSE API
# THIS WILL CHANGE TO HTTPS IN THE FUTURE
# HTTPS IS RECOMMENDED
main_bse_url = "http://basissetexchange.org"
# This allows for overriding the URL via an environment variable
# Feel free to just use the base_url below
base_url = o... |
6,739 | ac31cba94ee8ff7a2903a675954c937c567b5a56 |
def encrypt(key,plaintext):
ciphertext=""
for i in plaintext:
if i.isalpha():
alphabet = ord(i)+key
if alphabet > ord("Z"):
alphabet -= 26
letter = chr(alphabet)
ciphertext+=letter
return ciphertext
def decrypt(key,ciphertext):
plaintext=""
for i i... |
6,740 | f15f49a29f91181d0aaf66b19ce9616dc7576be8 | # Generated by Django 3.1.7 on 2021-04-16 05:56
from django.db import migrations
import django.db.models.manager
class Migration(migrations.Migration):
dependencies = [
('Checkbook', '0002_auto_20210415_2250'),
]
operations = [
migrations.AlterModelManagers(
name='transactio... |
6,741 | 46cdea08cab620ea099ad7fa200782717249b91b | #
# PySNMP MIB module SYSLOG-TC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SYSLOG-TC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:31:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
6,742 | 6e0d09bd0c9d1d272f727817cec65b81f83d02f5 | containerized: "docker://quay.io/snakemake/containerize-testimage:1.0"
rule a:
output:
"test.out"
conda:
"env.yaml"
shell:
"bcftools 2> {output} || true"
|
6,743 | 54d714d1e4d52911bcadf3800e7afcc2c9a615a5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 7 03:41:18 2020
@author: owlthekasra
"""
import methods as md
import add_label as al
import numpy as np
import pandas as pd
import random
sb_rd_1 = '/Users/owlthekasra/Documents/Code/Python/AudioStimulus/data/sine_bass/trials_2'
sb_rd_2 = '/Users... |
6,744 | 8a848eece6a3ed07889ba208068de4bfa0ad0bbf | # Copyright 2014 The Oppia Authors. 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 required by applicable ... |
6,745 | 4d066a189bf5151534e0227e67cdc2eed5cd387c | #!/usr/bin/python
# view_rows.py - Fetch and display the rows from a MySQL database query
# import the MySQLdb and sys modules
# katja seltmann April 16, 2013 to run on arthropod data in scan symbiota database
import MySQLdb
import sys
#connection information from mysql
#test database
connect = MySQLdb.connect("", u... |
6,746 | e810cde7f77d36c6a43f8c277b66d038b143aae6 | """
Base cache mechanism
"""
import time
import string
import codecs
import pickle
from functools import wraps
from abc import ABCMeta, abstractmethod
from asyncio import iscoroutinefunction
class BaseCache(metaclass=ABCMeta):
"""Base cache class."""
@abstractmethod
def __init__(self, kvstore, makekey, li... |
6,747 | 0656c3e1d8f84cfb33c4531e41efb4a349d08aac | from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
SQLALCHEMY_DATABASE_URL = f"sqlite:///{Path(__name__).parent.absolute()}/sql_... |
6,748 | d56fa4ea999d8af887e5f68296bfb20ad535e6ad | # 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 writing, software
# distributed under t... |
6,749 | ae45a4967a8ee63c27124d345ad4dc0c01033c0e | from mikeio.spatial import GeometryPoint2D, GeometryPoint3D
# https://www.ogc.org/standard/sfa/
def test_point2d_wkt():
p = GeometryPoint2D(10, 20)
assert p.wkt == "POINT (10 20)"
p = GeometryPoint2D(x=-5642.5, y=120.1)
assert p.wkt == "POINT (-5642.5 120.1)"
def test_point3d_wkt():
p = Geomet... |
6,750 | 0584ff5cb252fba0fe1fc350a5fb023ab5cbb02b | from django.db import models
class Category(models.Model):
name = models.CharField(max_length=50, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Categoria'
class Books(models.Model):
name = model... |
6,751 | 493552469943e9f9f0e57bf92b874c8b67943de5 | import os
from sources.lol.status import LOLServerStatusCollector
from util.abstract.feed import Feed
from util.abstract.handler import Handler
from util.functions.load_json import load_json
class LoLServerStatusHandler(Handler):
def load_servers(self):
servers_filepath = os.path.join(os.path.dirname(__... |
6,752 | ceca1be15aded0a842c5f2c6183e4f54aba4fd24 | v = 426
# print 'Yeah!' if dividable by 4 but print 'End of program' after regardless
if (v%4) == 0:
print ("Yeah!")
else:
print ("End of the program")
|
6,753 | af9430caff843242381d7c99d76ff3c964915700 | import os
from flask import Flask,render_template,request,redirect,url_for
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session,sessionmaker
app = Flask(__name__)
engine = create_engine("postgres://lkghylsqhggivp:d827f6dc5637928e95e060761de590b7d9514e9463c5241ed3d652d777a4a3a9@ec2-5... |
6,754 | 4c66ab6110e81bb88fc6916a1695e0f23e6e0e9d | from timeit import default_timer as timer
import numpy as np
bets1 = [ # lowest config possible
0.00000001,
0.00000004,
0.0000001,
0.0000005,
0.00000150,
0.00000500,
0.00001000
]
bets2 = [ # 2 is 10x 1
0.0000001,
0.0000004,
0.000001,
0.000005,
0.0000150,
0.0000500,... |
6,755 | 9087a7bf42070fdb8639c616fdf7f09ad3903656 | from .chair_model import run_chair_simulation, init_omega_t, \
JumpingModel, H_to_L
from .utils import load_hcp_peaks, Condition, average_peak_counts
|
6,756 | 24ad62342fb9e7759be8561eaf0292736c7dcb6d | import sys
def tackle_mandragora(health):
health.sort()
# for all tipping points, where we change over from eating to defeating
defeating = defeating_cost_precompute(health)
opt = 0
for i in range(0, len(health) + 1):
opt = max(opt, defeating_cost(i, defeating))
return opt
def defe... |
6,757 | 2fd490ca54f5d038997cec59a3e07c3f2c2d2538 | from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name ='park-home'),
path('login/', views.login, name ='park-login'),
] |
6,758 | 359f4fa75379cc2dd80d372144ced08b8d15e0a4 | def rank_and_file(l):
dict = {}
final_list = []
for each in l:
for num in each:
dict[num] = dict[num] + 1 if num in dict else 1
for key in dict:
if dict[key] % 2 != 0:
final_list.append(key)
final_list = sorted(final_list)
return " ".join(map(str, final_list))
f = open('B-large.in.txt', 'r')
f2 = open(... |
6,759 | 40f57ccb1e36d307b11e367a2fb2f6c97051c65b | # @Time : 2019/6/2 8:42
# @Author : Xu Huipeng
# @Blog : https://brycexxx.github.io/
class Solution:
def isPalindrome(self, x: int) -> bool:
num_str = str(x)
i, j = 0, len(num_str) - 1
while i < j:
if num_str[i] == num_str[j]:
i += 1
j -= 1... |
6,760 | 789f098fe9186d2fbda5417e9938930c44761b83 | # Unsolved:Didn't try coz of this warning:
# If you use Python, then submit solutions on PyPy. Try to write an efficient solution.
from sys import stdin
from collections import defaultdict
t = int(input())
for _ in range(t):
n = int(input())
arr = list(map(int, stdin.readline().strip().split()))
d... |
6,761 | 2180146da7ea745f5917ee66fd8c467437b5af4c | # Time :O(N) space: O(1)
def swap(arr, start, end):
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
def rotation(arr, k, n):
k = k % n
swap(arr, 0, k-1)
print(arr)
swap(arr, k, n-1)
print(arr)
swap(arr, 0, n-1)
print(arr)
if _... |
6,762 | cfdfc490396546b7af732417b506100357cd9a1f | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
import RPi.GPIO as gpio # 导入Rpi.GPIO库函数命名为GPIO
import time
gpio.setmode(gpio.BOARD) #将GPIO编程方式设置为BOARD模式
pin = 40
gpio.setup(pin, gpio.OUT) #控制pin号引脚
gpio.output(pin, gpio.HIGH) #11号引脚输出高电平
time.sleep(5) #计时0.5秒
gpio.output(pin, gpio.LOW) #11号引脚输出低电平
time.sleep(1) #计时1秒
... |
6,763 | 4af72cab6444922ca66641a08d45bcfe5a689844 |
from models import Cell,Board
import random
from pdb import set_trace as bp
status={'end':-1}
game=None
class Game_Service(object):
def __init__(self,row_num,col_num):
self._row_num=row_num
self._col_num=col_num
mine_percent=0.3
self._mine_num=int(mine_percent*float(self._row_nu... |
6,764 | 4e202cf7d7da865498ef5f65efdf5851c62082ff | def decimal_to_binary(num):
if num == 0: return '0'
binary = ''
while num != 0:
binary = str(num % 2) + binary
num = num // 2
return binary
def modulo(numerator, exp, denominator):
binary = decimal_to_binary(exp)
prev_result = numerator
result = 1
for i in range(len(bi... |
6,765 | 382597628b999f2984dba09405d9ff3dd2f35872 | #! /usr/bin/env python
import RPIO
import sys
RPIO.setwarnings(False)
gpio = int(sys.argv[1])
RPIO.setup(gpio, RPIO.OUT)
input_value = RPIO.input(gpio)
print input_value |
6,766 | c5f0b1dde320d0042a1bf4de31c308e18b53cbeb | version https://git-lfs.github.com/spec/v1
oid sha256:0c22c74b2d9d62e2162d2b121742b7f94d5b1407ca5e2c6a2733bfd7f02e3baa
size 5016
|
6,767 | 886024a528112520948f1fb976aa7cb187a1da46 | import json
parsed = {}
with open('/Users/danluu/dev/dump/terra/filtered_events.json','r') as f:
# with open('/Users/danluu/dev/dump/terra/game-data/2017-05.json','r') as f:
# with open('/Users/danluu/dev/dump/terra/ratings.json','r') as f:
parsed = json.load(f)
# print(json.dumps(parsed, indent=2))
print(js... |
6,768 | 5c20eefe8111d44a36e69b873a71377ee7bfa23d | import os, datetime
import urllib
from flask import (Flask, flash, json, jsonify, redirect, render_template,
request, session, url_for)
import util.database as db
template_path=os.path.dirname(__file__)+"/templates"
file=""
if template_path!="/templates":
app = Flask("__main__",tem... |
6,769 | eeb588a162fa222c0f70eb832a0026d0d8adbe9b | import sys
import os.path
root_dir = os.path.dirname(os.path.dirname(__file__))
jsondb_dir = os.path.join(root_dir, 'jsondb')
sys.path.append(jsondb_dir)
|
6,770 | deaa458e51a7a53dd954d772f9e3b1734508cf28 | '''
REFERENCE a table with a FOREIGN KEY
In your database, you want the professors table to reference the universities table. You can do that by specifying a column in professors table that references a column in the universities table.
As just shown in the video, the syntax for that looks like this:
ALTER TABLE a
A... |
6,771 | 2d5e7c57f58f189e8d0c7d703c1672ea3586e4ac | """
Simple neural network using pytorch
"""
import torch
import torch.nn as nn
# Prepare the data
# X represents the amount of hours studied and how much time students spent sleeping
X = torch.tensor(([2, 9], [1, 5], [3, 6]), dtype=torch.float) # 3 X 2 tensor
# y represent grades.
y = torch.tensor(([92], [100], [89]... |
6,772 | 2c2b075f9ea9e8d6559e44ad09d3e7767c48205e | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
import numpy as np
def weight_init(layers):
for layer in layers:
if isinstance(layer, nn.BatchNorm1d):
layer.weight.data.fill_(1)
layer.bias.data.zero_()
elif isinstance(layer, nn.Lin... |
6,773 | 1f21fdc9a198b31bb0d5bd6dd8f46a1b3b28ec94 | import kwic
mystr = "hello world\nmy test\napples oranges"
#asseirt(kwic0.kwic(mystr) == [])
#assert(kwic1.kwic(mystr) == [mystr])
#assert(len(kwic3.kwic(mystr))==2)
assert len(kwic.kwic(mystr)) == 3
|
6,774 | 8fe9d21bb65b795a6633ab390f7f5d24a90146d5 | x = '我是一个字符串'
y = "我也是一个字符串"
z = """我还是一个字符串"""
#字符串str用单引号(' ')或双引号(" ")括起来
#使用反斜杠(\)转义特殊字符。
s = 'Yes,he doesn\'t'
#如果你不想让反斜杠发生转义,
#可以在字符串前面添加一个r,表示原始字符串
print('C:\some\name')
print('C:\\some\\name')
print(r'C:\some\name')
#反斜杠可以作为续行符,表示下一行是上一行的延续。
s = "abcd\
efg"
print(s)
#还可以使用"""...""... |
6,775 | bc0bfb0ff8eaf21b15b06eea2ea333381c70bc75 | __author__='rhyschris'
""" Defines the set of actions.
This functions exactly the same as
Actions.cs in the Unity game.
"""
from enum import Enum
class Actions(Enum):
doNothing = 0
crouch = 1
jump = 3
walkTowards = 0x1 << 2
runTowards = 0x2 << 2
moveAway = 0x3 << 2
blockUp = 0x1 ... |
6,776 | bff9fb50f1901094c9ab3d61566509835c774f21 | import time
import os
import random
def generate_sequence(difficulty):
print("Try to remember the numbers! : ")
random_list = random.sample(range(1, 101), difficulty)
time.sleep(2)
print(random_list)
time.sleep(0.7)
os.system('cls')
time.sleep(3)
return random_list
def get_list_from_... |
6,777 | 2ed0ae48e8fec2c92effcbb3e495a1a9f4636c27 | import flask
import flask_sqlalchemy
app = flask.Flask(__name__)
app.config.from_pyfile('settings.py')
db = flask_sqlalchemy.SQLAlchemy(app)
|
6,778 | 8f57e120a1a84eb0b9918128580c152aabc6a724 | from django.db import models
class UserData(models.Model):
username = models.CharField(max_length=24)
email = models.EmailField(max_length=32, blank=True, null=True)
password = models.CharField(max_length=32)
created_data = models.DateTimeField()
email_is_confirm = models.CharField(max_length=20, ... |
6,779 | 033973ddc81a5fdf0e40009c4f321215fe3f4217 | class Solution(object):
def checkSubarraySum(self, nums, k):
if not nums or len(nums) == 1:
return False
sum_array = [0]*(len(nums)+1)
for i, num in enumerate(nums):
sum_array[i+1] = sum_array[i]+num
if k == 0:
if sum_array[-1] == 0:
... |
6,780 | f531af47431055866db72f6a7181580da461853d | #!/usr/bin/python
from setuptools import setup, find_packages
import os
EXTRAS_REQUIRES = dict(
test=[
'pytest>=2.2.4',
'mock>=0.8.0',
'tempdirs>=0.0.8',
],
dev=[
'ipython>=0.13',
],
)
# Tests always depend on all other requirements, except dev
for k,v in EX... |
6,781 | ec200ee66e3c4a93bbd8e75f0e8b715f54b5479d | #
# In development by Jihye Sofia Seo https://www.linkedin.com/in/jihyeseo
# forked from the code of Al Sweigart
# http://inventwithpython.com/pygame/chapter10.html
# whose books are very helpful for learning Python and PyGame. Many thanks!
# Main change is that his version uses flood fill algorithm, which coul... |
6,782 | 424a0e8a7a80e24aec4bdb9b8c84fd9a5e6090c6 | import logging
import time
import random
import pickle
import os
from sys import maxsize
import torch
from tensorboardX import SummaryWriter
from baselines.common.schedules import LinearSchedule
from abp.utils import clear_summary_path
from abp.models.feature_q_model import feature_q_model
from abp.adaptives.common.p... |
6,783 | f44a8837056eb77fbf0ff37b9c57891cc3a3d6b2 | import logging
from datetime import datetime
from preprocessing import death_preprocessing
from preprocessing_three_month import death_preprocessing_three_month
from death_rule_first_55 import death_rule_first_55
from death_rule_second import death_rule_second_new
from death_escalation import death_escalation
if __n... |
6,784 | cc58e3944ee2bfb55cc2867395782a94c196e635 | ########################################################################################################################
# DEVELOPER README: #
# This is the main script, where the GUI is initialised from. All of the main ... |
6,785 | 178f9dcd9cbea140abebd509b56979417b5d7503 | # Python implementation of Bubble Sort
def bubbleSort(arr):
k = len(arr)
# Traverse through all elements
for i in range(k):
# Last i elements are already in correct place
for j in range(0, k - i - 1):
# Swap if element is greater than next element
if arr[j] > arr[j ... |
6,786 | 4436fa36ec21edb3be467f74d8b9705780535f22 | from common.utils import create_brokers
from Bot import DataGatherBot, ArbitrageBot
import api_config as config
### PAPER 이라고 정의한
# brokers = create_brokers('PAPER', config.CURRENCIES, config.EXCHANGES)
# bot = ArbitrageBot(config, brokers)
# brokers = create_brokers('BACKTEST', config.CURRENCIES, config.EXCHANGES)
#... |
6,787 | 05186093820dffd047b0e7b5a69eb33f94f78b80 | #!/usr/bin/env python
'''
@author : Mitchell Van Braeckel
@id : 1002297
@date : 10/10/2020
@version : python 3.8-32 / python 3.8.5
@course : CIS*4010 Cloud Computing
@brief : A1 Part 2 - AWS DynamoDB ; Q2 - Query OECD
@note :
Description: There are many CSV files containing info from the OECD about agricultural p... |
6,788 | e5bf4518f3834c73c3743d4c711a8d1a4ce3b944 | # Generated by Django 3.2.5 on 2021-08-05 23:59
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('lectures', '0003_auto_20210805_1954'),
]
operations = [
migrations.RenameField(
model_name='lecture',
old_name='is_requird',... |
6,789 | a8106c8f14e15706b12e6d157b889288b85bc277 | import random
import datetime
import userval
import file
from getpass import getpass
#SORRY FOR THE REDUNDANT CODE, I RAN OUT OF OPTIONS
def register():
global first,last,email,pin,password,accountName #prepared_user_details
first=input("input firstname:")
last=input("input lastname:")
... |
6,790 | 8030bdb6c9f0b7114916d7abc245ff680d1fc917 | workdir = './model/adamW-BCE/model_seresnext50_32x4d_i768_runmila_2fold_50ep'
seed = 300
n_fold = 2
epoch = 50
resume_from = None
batch_size = 32
num_workers = 32
imgsize = (768, 768) #(height, width)
loss = dict(
name='BCEWithLogitsLoss',
params=dict(),
)
optim = dict(
name='AdamW',
params=dict(
... |
6,791 | 804c75b3ab0b115e5187d44e4d139cfb553269a9 | from django import template
from ..models import Article
# 得到django 负责管理标签和过滤器的类
register = template.Library()
@register.simple_tag
def getlatestarticle():
latearticle = Article.objects.all().order_by("-atime")
return latearticle |
6,792 | 52f3000514fd39083daa6316d551f1685c7cea23 | from random import randint
class Game(object):
def __init__(self, players):
if len(players) < 2:
raise ValueError('Number of player must be at least 2')
self.play_order = players
self.player_data = {}
for player in self.play_order:
# ... |
6,793 | 7e33475a6ab7ad0d1e9d7d00b8443329e265fe69 | def printPar():
for i in range(len(par)):
print "par[{0:d}] = {1:d}".format(i,par[i])
def printImpar():
for i in range(len(impar)):
print "impar[{0:d}] = {1:d}".format(i,impar[i])
par = []
impar = []
for i in range(15):
n= int(raw_input())
if n%2 == 0:
if len(par)<4:
... |
6,794 | 430dff54da986df4e3a68018d930735c757d49d0 | import time
import json
from threading import Thread
try:
with open('file.json') as f:
name = json.load(f)
except:
f = open("file.json", "w+")
name = {}
def create(k, v, t='0'):
if k in name:
print("ERROR:The data already exists")
else:
if k.isalpha():
... |
6,795 | 76382f353c47747ee730d83c2d3990049c4b0d98 | ##
## Copyright (C) by Argonne National Laboratory
## See COPYRIGHT in top-level directory
##
import re
import os
class G:
pmi_vers = []
cmd_list = []
cmd_hash = {}
class RE:
m = None
def match(pat, str, flags=0):
RE.m = re.match(pat, str, flags)
return RE.m
def search(pat... |
6,796 | 06caee24b9d0bb78e646f27486b9a3a0ed5f2502 | #ribbon_a and ribbon_b are the two important variables here
ribbon_a=None
ribbon_b=None
#Notes:
# - As it turns out, the internal ADC in the Teensy is NOT very susceptible to fluctuations in the Neopixels' current...BUT...the ADS1115 IS.
# Therefore, I think a better model would ditch the ADS1115 alltogether ... |
6,797 | 2e744c0cbddf64a9c538c9f33fa19ff78c515012 | """
Stores custom FASTA sequences under a uuid in the database.
Part of the tables used for custom jobs.
"""
import uuid
from pred.webserver.errors import ClientException, ErrorType, raise_on_too_big_uploaded_data
from pred.queries.dbutil import update_database, read_database
from Bio import SeqIO
from io import String... |
6,798 | 5d8715dd02feff4e13919858051abeb5b6828011 | # Imports
import numpy as np
from ctf.functions2d.function2d import Function2D
# Problem
class StyblinskiTang(Function2D):
""" Styblinski-Tang Function. """
def __init__(self):
""" Constructor. """
# Information
self.min = np.array([-2.903534, -2.903534])
self.value = -39.16... |
6,799 | 0dbdd7f7adffed850f126a2054c764b421c6ab84 | from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.classify import NaiveBayesClassifier
from nltk.probability import FreqDist
import csv
f = open('trolls.csv', 'r')
file = csv.reader(f)
sentences=[]
remarks=[]
psObject = PorterStemmer(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.