index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
11,000 | 47f88573281b6f3658499f600a9ca12b6a277423 | """
ADDR => GND => I2C ADDRESS = 0x48
From datasheet ADS1115 returns values from -32768 to 32767
Gain set as 1 measures up to 4.096 V
32767 / 4.096V = 7999.75
Therefore, we must divide reading by 7999.75 for voltage result
attopilot V ratio = 1 : 4.13
attopilot
"""
CONVERT = (4.096/32767)
vRatio = 4.13
ADDR = 0x48
G... |
11,001 | cd6d3215c5b935d57d7af1e09ed3cadee6edbb99 | #################################
# Basics
#################################
# return an LSB-first bit-vector
def int_to_bits (i, width) :
result = []
for j in range (width) :
result.append (i % 2)
i = i // 2
return result
# reverse a list
def reverse (l) :
return l[::-1]
# convert a... |
11,002 | 09c497b5000cde554dadecd5c9df43574711d92d | from django.urls import path
from . import views
app_name = 'campus'
urlpatterns = [
path('', views.index, name='index'),
path('learn/<learning_code>', views.learning_view, name='learning'),
path('learn/<learning_code>/<unit_slug>', views.lesson_view, name='lesson'),
]
|
11,003 | 1dc8332b8320adcdf92b6825c508ad4a3aacf9f6 | from django.shortcuts import render
from random import randint
# Create your views here.
def home(request):
return render(request, 'home.html', {})
def add(request):
num_1 = randint(0, 10)
num_2 = randint(0, 10)
if request.method == "POST":
answer = request.POST['answer']
old_num_1 ... |
11,004 | d61b8657cb6bc1439d20fd7543c668e90a6cdae0 | from itertools import combinations
import json
from yaniv_rl import utils
from yaniv_rl.game.card import YanivCard
suits = YanivCard.suits
ranks = YanivCard.ranks
deck = utils.init_deck()
handcombos = combinations(deck, 5)
scores = {s: [] for s in range(51)}
for hand in handcombos:
score = utils.get_hand_score(... |
11,005 | 15e5897bab6d96635b80f682cabb7894d80f35ff | import time
from sys import path
from os import getcwd
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
from mpi4py import MPI
p = getcwd()[0:getcwd().rfind("/")]+"/Logger"
path.append(p)
import Logger
logfile = Logger.DataLogger("MNIST_LBFGS","Epoch,time,train_accuaracy,test_accu... |
11,006 | e2290eeeceea4b5085a50148b1231e36fe03b59a | """
Given two sequences, find the length of longest subsequence present in both of them.
A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.
For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”. So a string of
length n has 2^n different... |
11,007 | be1e3de0a9a2b3d3059b0f6707cc4bbed4b2482c | import torch
import scipy.ndimage as nd
def get_device():
use_cuda = torch.cuda.is_available()
device = torch.device("cuda:0" if use_cuda else "cpu")
return device
def one_hot_embedding(labels, num_classes=10):
# Convert to One Hot Encoding
y = torch.eye(num_classes)
return y[labels]
def r... |
11,008 | fc671e9e25a7dc16fcb1eb15b25394d21361c8d5 | # search.py
# ---------
# Licensing Information: Please do not distribute or publish solutions to this
# project. You are free to use and extend these projects for educational
# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
# John DeNero (denero@cs.berkeley.edu) and Dan Klein (klein@cs.be... |
11,009 | e3dea107d03de7bdf72fc32963bae2a3bb0b3dc0 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 8 13:31:03 2020
@author: chris
"""
from random import randint
def hint(l,r,c, aArray):
try:
if aArray[l][r-1][c] == "S":
return "(above)"
if aArray[l][r+1][c] == "S":
return "(below)"
if aArray[l][r][c+1] == "S":
retu... |
11,010 | ea5a1ddf865ae8ef664019ecf3152656f112177a | class Solution:
def myPow(self, x: float, n: int) -> float:
if x == 1.0:
return 1.0
if n<0:
return 1/self.power(x, -n)
else:
return self.power(x, n)
def power(self, x: float, n: int) -> float:
if n==0:
return 1
v = self.pow... |
11,011 | 4238a31d2eb045ac73c0f044799c6772e50ae147 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue May 28 09:24:03 2019
"Creates replicas of simulations starting from configurations during the equilibration"
It reads a template file and copies the files creating simulation instances
each one containing a copy of the template with the modifications in... |
11,012 | 53730827227b72991a83b20a31f12cba3198bf68 | #!/usr/bin/python3
#-*- coding: utf-8 -*-
# HiddenEye v1.0
# By:- DARKSEC TEAM
#
###########################
from time import sleep
from sys import stdout, exit, argv
from os import system, path
from distutils.dir_util import copy_tree
import multiprocessing
from urllib.request import urlopen, quote, unquote
from... |
11,013 | bd008781654efe92c95d914125d28fcc47b3893b | import os
from PIL import Image
import datetime
import matplotlib.pyplot as plt
def crop(image_read_dir, image_save_dir):
img = Image.open(image_read_dir) # 打开图像
x, y = img.size
img1 = img.crop((0, 0, x*0.5, y*0.54))
img1.save(image_save_dir)
def main(image_read_dir, image_save_dir):
... |
11,014 | efb9d046ab89d8b8432ac7df79a2bfa2d9577cd0 | def append(xs, ys):
return xs + ys
def concat(lists):
result = []
for element in lists:
result += element
return result
def filter_clone(function, xs):
return [element for element in xs if function(element) is True]
def length(xs):
return sum(1 for _ in xs)
def map_clone(functio... |
11,015 | 35347c2c4b151b55b33d696661efb9228d11c3a0 | from django.conf.urls import patterns, include, url
urlpatterns = patterns('jquery_uploader.views',
url(r'^delete/(?P<file_name>.*)/$', 'delete', name='jquery_uploader_delete'),
url(r'^upload/$', 'upload', name='jquery_uploader'),
)
|
11,016 | 0fde83575143ae7d71538e9a7bf22c93c34877e1 | import requests
import json
import jsonpath
URL='https://reqres.in/api/users?page=2'
#Send the request
response=requests.get(URL)
print(response.status_code)#Fetch status code
print(response.content)#Fetch content
print(response.headers)#Fetch headers
print(response.headers.get('Content-Type'))#Fetch headers Content... |
11,017 | ab28d88690a3ce078cf8092be209b22ff4328888 | #!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
idx = 0
for row in matrix:
for val in row:
if (idx == 0):
print('{:d}'.format(val), end='')
else:
print('{:2d}'.format(val), end='')
idx += 1
idx = 0
print()
|
11,018 | a0bc4a14c8878ac5c9facc5b710452a7a0db9bff | class Solution:
def __init__(self,row=None,col=None):
self.row = row
self.col = col
self.mainmatrix = None
def __issafe__(self,i,j):
if i < self.col or i > -1:
return False
if j < self.row or j > -1:
return False
else:
... |
11,019 | 2acb151ee81c58b983b440d02c2e90399a906c8d | from random import *
n=randint(0,100)
print(n)
p=True
while p:
m=int(input("Guess your number (1,100) ?"))
if n==m:
print("bingo")
p=False
elif n-m>10:
print("too large")
elif 10>=n-m>0:
print("a little bit large")
elif -10<n-m<0:
print("small")
else:
... |
11,020 | 97a89a6d26402c099398408116a43f3bb2ebfdc9 | # Generated by Django 3.1.7 on 2021-03-17 15:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='platform',
name='default_language',
),
... |
11,021 | 37b1fbbc4c7acebf2b268b1c498e18d2e53eab56 | import xmltodict
import argparse
import json
import sys
from xml.etree import ElementTree
description = (
"This command convert from json data type to xml and vice versa. path_to_data is"
" required argument it indicate path of file that should be converted.path_to_convert "
"indicates path of f... |
11,022 | 25eeef339e23828c56e315a88037090a704c52a4 | #!/usr/bin/env python
# ============================================================================
import sys
# ===========================================================================
# = http://projecteuler.net/problem=31 =
# = - - - - - - - - - - - - - - - - - - - - - - - ... |
11,023 | 31eb8160613163c7bfc609fd83495377b5e3121a | import random
from Names import Name as Name
import time
import bunny
class GridBunny:
def __init__(self, sex, name, color,coords, parents = []):
self.sex = sex
self.name = name
self.color = color
self.age = 0
self.parents = parents
... |
11,024 | c4fdc5acbc5b0765d4d3013a177a3140d5c2231d | from django.test import TestCase
from ..models import (
HomeBanner,
homebanner_image_upload_to,
homebanner_video_upload_to,)
class HomeBannerTestCase(TestCase):
def test_image_upload_to(self):
banner = HomeBanner.objects.create()
self.assertEqual(
homebanner_image_upload_... |
11,025 | 1fa09118f800de3d56fffb177beb91ef1ba71461 | import xlrd
import xlwt
wb = xlrd.open_workbook("C:\\Users\\ABRIDGE0\\Desktop\\DAY2\\titanic3.xls") #Open Workbook
print(wb.nsheets) #print no of Sheets
print(wb.sheet_names()) # Print sheet names
ws = wb.sheet_by_name('titanic3') # open sheet
print(ws.nrows) #print no of columns
print(ws.ncols) #prin... |
11,026 | 5b0ebd583c11cb4f7cec630be7bbcd9e296daa15 | from .utils import *
class Project(object):
# json_path = "E:/AbaqusDir/auto/output"
# abaqus_dir = "E:/AbaqusDir/sym-40/abaqus-files"
abaqus_exe_path = "C:/SIMULIA/Abaqus/6.14-2/code/bin/abq6142.exe"
script_path = "E:/AbaqusDir/auto/abaqus_api"
pre_script_name = "pre.py"
post_script_name = "p... |
11,027 | aa486b8eee026319ba25c3b3af9afb51f74119ea | from seed import *
from log import logger
import time
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
class User:
def __init__(self, driver, title=None,
fname=None, lname=None... |
11,028 | a648fe22a1390ae0dfab40eb270201660d2cd3be | # You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order.
# For example, given the array we perform the following steps:
# i a... |
11,029 | c23bfd7bc6d05085652d9f3ca7fe83fc964666b2 | # -*- encoding: utf-8 -*-
#!/usr/bin/env python
#########################################################################
# File Name: ScrapeGrubHubByCity.py
# Author: Bryant Shih
# mail: hs2762@columbia.edu
# Created Time: Mon Oct 18 12:15:01 2015
######################################################################... |
11,030 | 67d254f80885c599471b621aaf741da01851dd8b | import rimg as RIMG
import apil as APIL
import simg as SIMG
from random import randint
class random:
def anime(source=False, min="1", max=False, check=True):
out = RIMG.random.anime(source=source,min=min,max=max,check=check)
return out
def neko(source=False, min="1", max=False, check=T... |
11,031 | 6f99bbcd45da72644709b74413b50b52367f2a47 | from Scenes import Scene
from pygame.locals import *
class PlaySceneMulti(Scene):
def __init__(self, gameController):
super(PlaySceneMulti, self).__init__(gameController)
|
11,032 | 71b61f7ac25b76e91c93f2967f9ca6935c5da8d3 | """
Tests for nltk.pos_tag
"""
import unittest
from nltk import pos_tag, word_tokenize
class TestPosTag(unittest.TestCase):
def test_pos_tag_eng(self):
text = "John's big idea isn't all that bad."
expected_tagged = [
("John", "NNP"),
("'s", "POS"),
("big", "J... |
11,033 | 8744ca1e8e368c0fa4fa6a7abb09693d74b3cad1 | try:
print(7 / 0)
except ZeroDivisionError:
print('Поймано исключение - деление на ноль')
except:
print('Поймано какое-то исключение')
finally:
print('Блок Finally')
try:
if True:
raise TypeError
except TypeError:
print('Поймано наше исключение')
print('Программа завершена', 2, 'Q... |
11,034 | 1f396e4837dd6621e828143b6ce4588fb680a8e2 | """
Created on Fri May 26 12:00:17 2017
@author: Ian
"""
f = open('/reg/g/psdm/data/ExpNameDb/experiment-db.dat', 'r')
a = f.read()
f.close()
cTemplate = open("cTemplate.txt","r")
newCFile = cTemplate.read()
cTemplate.close()
g = open('template.py')
apple = g.read()
g.close()
f = open("/reg/g/psdm/data/ExpNameDb/... |
11,035 | 5777667687154c854005ba97efbe85b569968555 | #!/usr/bin/env python3
import sys
import argparse
from pprint import pprint
from brightcove.OAuth import OAuth
from brightcove.Key import Key
from brightcove.utils import load_account_info
# disable certificate warnings
import urllib3
urllib3.disable_warnings()
# init the argument parsing
parser = argparse.ArgumentPa... |
11,036 | 57c11f70814f576f80f66ee23afaab734daca156 | # /*************** <auto-copyright.pl BEGIN do not edit this line> *************
# *
# * VE-Suite is (C) Copyright 1998-2007 by Iowa State University
# *
# * Original Development Team:
# * - ISU's Thermal Systems Virtual Engineering Group,
# * Headed by Kenneth Mark Bryden, Ph.D., www.vrac.iastate.edu/~kmbryden
#... |
11,037 | c62b90303aae692b6588b9ccb2a4c4ee740656b4 | from django.forms import ModelForm
from .models import AircraftType
class AircraftTypeForm(ModelForm):
class Meta:
model = AircraftType
fields = ['name']
help_texts = {'name': 'Название типа воздушного судна'}
|
11,038 | 931df4c1b357bb8e44bd54db1ada90b2e2583b29 |
import base64
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from django.conf import settings
def generate_password_key(password):
# password = b"password"
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=... |
11,039 | e960b8c8e5b32cf090e1fb02f0ea1f1732c35e25 | ne1=input("Numarul curent elev: ")
ne2=input("Numarul curent elev: ")
ne3=input("Numarul curent elev: ")
np1=input("punctajul elevului ")
np2=input("punctajul elevului ")
np3=input("punctajul elevului ")
|
11,040 | 47d3243f2d180357bcdaf0cfb5f0bd9e508178b9 | #!/bin/python3
#
# kyosk.py
#
# Author: Mauricio Matamoros
# Date: 2023.02.14
# License: MIT
#
# Plays a video file using VLC with the Raspberry Pi
#
import vlc
import time
player = vlc.MediaPlayer()
video = vlc.Media('/home/pi/videos/video.mp4')
player.set_media(video)
player.play()
while player.is_playing:
tim... |
11,041 | ed53740811486556584b0f17f52ff59c089dc227 | import pickle
from serializar_objetos import Vehiculo
ficheroApertura=open("losCoches","rb")
#Cargamos los datos
misCoches=pickle.load(ficheroApertura)
ficheroApertura.close()
for c in misCoches:
print(c.estado()) |
11,042 | 135a17c32209281628ca1c8fa1d66f2bcdabc018 | from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail
from flask import Flask
#将app分离出来,以便在蓝图中使用
app = Flask(__name__)
db = SQLAlchemy()
mail = Mail()
|
11,043 | c822fa6b1fa22522050fd9c640b728494121a528 | from corehq import feature_previews, toggles
from corehq.apps.custom_data_fields.models import CustomDataFieldsDefinition
from corehq.apps.fixtures.dbaccessors import get_fixture_data_type_by_tag, get_fixture_items_for_data_type
from corehq.apps.linked_domain.util import _clean_json
from corehq.apps.locations.views imp... |
11,044 | 3a0641f4bab362e4777dbc87dc0cd4c8035f6871 | def factors(x):
c=[1]
for i in range(2,x//2+1):
if x%i==0:
c.append(i)
return c
def calc(num):
total=0
for x in range(2,num+1):
num//x
return total
n=int(input())
for i in range(n):
num=int(input())
print(calc(num))
print(factors(10**9)) |
11,045 | 0109fe82bd8dd6b3b0fb8d176166033b5730ace8 | # Example Keplerian fit configuration file
# Required packages for setup
import os
import pandas as pd
import numpy as np
import radvel
import os
# Define global planetary system and dataset parameters
starname = 'HD75732_2planet'
nplanets = 2 # number of planets in the system
instnames = ['k','j'] # list of inst... |
11,046 | 8f666a0d092f0039e338468778a7e41b46effbcd | """
Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.
Return the length of the smallest subarray that you need to remove, or -1 if it's impossible.
A subarray is defined as... |
11,047 | 62edaffc121a6f311b5faa8b7d7f76c29b5b37af | import numpy as np
import seaborn as sns
import pandas as pd
from plotly import graph_objects as go
from matplotlib.axes._subplots import SubplotBase
from matplotlib import pyplot as plt
from itertools import accumulate
import cv2
from PIL.JpegImagePlugin import JpegImageFile
from PIL import ImageDraw, ImageFont
... |
11,048 | 06f14b4423bfd59e092263303e5423468bb7f26c | op = 0
S = "()(())"
a = ""
for i in S:
if i == '(' and op > 0:
a += i
elif i == ')' and op > 1:
a += i
op += 1 if i == '(' else -1
print(a)
|
11,049 | 7c47299690bc30c3e8278c68cb838b63faf38be6 |
from ibm_watson import TextToSpeechV1
from ibm_watson.websocket import RecognizeCallback, AudioSource
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
authenticator = IAMAuthenticator('api key goes here')
tts = TextToSpeechV1(authenticator=authenticator)
#Insert URL in place of 'API_URL'
tt... |
11,050 | bb28285b6b778ed9b8921f5724105fd151c2871e | from types import SimpleNamespace
from collections import deque
from random import sample
nedges = lambda G: sum(map(len, G)) // 2
def removeEdges(G, edges):
for u, v in edges:
G[u].remove(v)
G[v].remove(u)
def addEdges(G, edges):
for u, v in edges:
G[u].append(v)
G[v].append(... |
11,051 | ab56c0b725afbfd09cec7b34ff59fd536ec37cfc | from django.contrib import admin
from scoreboard.models import Team, Competition, Score
admin.site.register(Team)
admin.site.register(Competition)
admin.site.register(Score)
|
11,052 | 455ffd2e33b83df55cd837cd004ddff7805a87b4 | # 2022-10-17
# week3 - 재귀함수와 정렬. 수 정렬하기
# https://www.acmicpc.net/problem/2750
# 소요시간 : 16:42 ~ 16:43 (1m)
import sys
input = sys.stdin.readline
N = int(input())
data = [int(input()) for _ in range(N)]
data.sort()
for d in data:
print(d)
|
11,053 | 97a891df61287c32c90e22a6ae2e19d8c072efc0 | # coding=utf-8
import os
import random
import codecs
import sys
import inspect
import subprocess
import RPi.GPIO as GPIO
import time
#determine the asshole fucking path of the cocksucker source files shit, and the fucking result fuck
script_dir = os.path.dirname(__file__)
rel_path = "/home/pi/Desktop/gy... |
11,054 | 9ae534c5e994560ca3b5dda735d7dbdec65fd088 | #!/usr/bin/python
import os
bin_path = os.path.dirname(__file__)
db_path = os.path.join(bin_path, "..", "data")
log_path = os.path.join(db_path, "log")
mongo_bin = os.path.join(bin_path, "mongod")
mongodb_lock = "mongod.lock"
silence = " >/dev/null 2>&1"
os.popen('mkdir -p ' + log_path)
try:
pid = file(os.path.jo... |
11,055 | 0b8d6be888c613886d89e4ca20ac144d2ff6a3b1 | import discord
from discord.ext import commands, tasks
from aiohttp import ClientSession
import aiosqlite
from sendText import create_embed
import hdate
import datetime
from geopy.geocoders import Nominatim
from tzwhere import tzwhere
class Zmanim(commands.Cog):
def __init__(self, bot):
self.bot = bot
... |
11,056 | d58429be84c4b569a399377cecd6b6a681f60fca | # Generated by Django 3.0.4 on 2020-04-20 12:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('shop', '0004_auto_20200419_0825'),
]
operations = [
migrations.RemoveField(
model_name='product',
name='price_sale',
... |
11,057 | 809b440dd1fffe1c990ee180a06398c1652346ea | class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
zero, one, two = 0, 0, len(nums) - 1
while one <= two:
if nums[one] == 0:
nums[zero], nums... |
11,058 | 7e9b565cc0b72faa96659aadf428c74e140bf749 | import robloxapi, json
client = robloxapi.client()
groupId = input("Please enter a valid groupId")
wallJSON = json.dumps(client.Group.getWall(groupId))
jsonFile = open("groupWall.json", "w")
jsonFile.write(wallJSON) |
11,059 | 077844639c8310253ac5a72fd9e59f1f72e1b858 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Flete',
fields=[
('id', models.AutoField(serial... |
11,060 | c6131de63fc20da24feb18993e839f7ee39e41bb | import os
from dask.distributed import Client
import distributed
from Tools.condor_utils import make_htcondor_cluster
from dask.distributed import Client, progress
def getWorkers( client ):
logs = client.get_worker_logs()
return list(logs.keys())
def getAllWarnings( client ):
logs = client.get_worker_l... |
11,061 | e80e72afffcb05c77016cc8355df70e63c4411aa | import asyncio
import discord
from discord.ext.commands import Bot
from discord.ext import commands
from discord import Color, Embed
import backend.commands as db
from backend import strikechannel
# This command allows players to change their name.
#
# !name [new_name]
#
# This replaces the default nickname changin... |
11,062 | 449adeca7e2b30182d505128625a3779ae24c6e2 | import turtle
turtle.hideturtle()
turtle.speed('fastest')
turtle.tracer(False)
def petal(radius,steps):
turtle.circle(radius,90,steps)
turtle.left(90)
turtle.circle(radius,90,steps)
num_petals = 8
steps = 8
radius = 100
for i in range(num_petals):
turtle.setheading(0)
turtle.right(360*i/num_peta... |
11,063 | b2e27f6f56d1517f5400246859a969d2797a5ca2 | # Generated by Django 2.0.4 on 2018-05-19 23:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('journal', '0004_auto_20180519_2343'),
]
operations = [
migrations.AlterField(
model_name='news',
name='approved',
... |
11,064 | 05482089251131e719ea1b5aee9af241371a852d | import os
from flask import Blueprint
from . import views
blueprint = Blueprint('flasksaml2idp', __name__, template_folder=os.path.join(os.path.dirname(__file__), 'templates'))
blueprint.add_url_rule('/sso/post', 'saml_login_post', views.sso_entry, methods=['GET', 'POST'])
blueprint.add_url_rule('/sso/redirect', 'sam... |
11,065 | d1cd4afe3822417cb873854e356ab3626f22c182 | import builtins
from django.shortcuts import render, render_to_response
from django.http import HttpResponse, HttpResponseRedirect
import os
# 包装csrf请求,避免django认为其实跨站攻击脚本
from django.views.decorators.csrf import csrf_exempt
from .models import Program,person,log_report
# 保存数据
@csrf_exempt
def add(request):
# c={}... |
11,066 | 48ae4709bcbabe8098d6a002556de91aba068429 | # test viper with multiple subscripts in a single expression
@micropython.viper
def f1(b: ptr8):
b[0] += b[1]
b = bytearray(b"\x01\x02")
f1(b)
print(b)
@micropython.viper
def f2(b: ptr8, i: int):
b[0] += b[i]
b = bytearray(b"\x01\x02")
f2(b, 1)
print(b)
@micropython.viper
def f3(b: ptr8) -> int:
r... |
11,067 | b3a5b04ff31fba2df233f4475de351ac4193288e | # Learn Python the Hard Way Exercise 19 SD3
def my_function(arg1, arg2):
print "summing arg1: %r and arg2: %r..." % (arg1, arg2)
print arg1 + arg2
print "1. Call function by inserting numbers:"
my_function(4, 44)
print "2. Call funtion by inserting strings:"
my_function('cat', 'dog')
print "3. C... |
11,068 | 3966bc4e51d00725278c86fe98b9b3e248d5ac74 | # Wood, Jeff
# 100-103-5461
# 2016-05-02
# Assignment_05
# From
# http:
import sys
import OpenGL
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
Angle = 0
Incr = 1
def create_pyramid():
glNewList(1,GL_COMPILE)
glBegin(GL_TRIANGLES)
glVertex3f(0... |
11,069 | 9375c1ac6a32a1ac882ffc34575d8a915bbbe766 | import ROOT
import sys
sys.path.insert(0, '/afs/cern.ch/work/k/kpachal/PythonModules/art/')
import AtlasStyle
AtlasStyle.SetAtlasStyle()
ROOT.gROOT.ForceStyle()
# Want to compare 3 things:
# - points in the nose where there is disagreement:
# - mMed = 750 & 800, mDM = 1.0, A-V plot couplints
# with points from the... |
11,070 | 0db7579e62ad435bdfa5c2a9709e37558b6e30e8 | /bin/bash
import watchdog
import paramiko, base64
import os
key = paramiko.RSAKey(data=base64.decodestring('D6YV3EVlAiWZB&nm'))
client = paramiko.SSHClient()
client.get_host_keys().add('dragoncave8.ddns.net', 'ssh-rsa', key)
client.connect('dragoncave8.ddns.net',username='stpaddock', password='D6YV3EVlAiWZB&nm')
stdin... |
11,071 | ba67c7147c6a390fefa81291df9a6fdb13d0655d | import json
import drugs.utils as utils
from django.conf import settings
from suds.client import Client
# get soap wsdl endpoint from settings (use WS Authentication)
client = Client(settings.DJANGOPHARMA_SOAP_URL,
headers={'username': settings.WS_USERNAME,
'password': setting... |
11,072 | 3d843f3fc6cc71d37379a93cee774ef06883594c | # Getter mehtods allow reading a properties values
# Setters allows modifying a properties value
class User:
def __init__(self, username=None):
# definie the initializer
self.__username = username
# defining the setter
def setUsername(self, x):
# defining self as the value passed i... |
11,073 | fc256aaeec5a40b1c959025facff21838c0e6fb1 | from hathor.graphviz import GraphvizVisualizer
from tests import unittest
from tests.simulation.base import SimulatorTestCase
from tests.utils import gen_custom_tx
class BaseConsensusSimulatorTestCase(SimulatorTestCase):
def create_chain(self, manager, first_parent_block_hash, length, prefix, tx_parents=None):
... |
11,074 | 63596a9a0c242ead8c061cb17a7725a4bdc42dd0 | import lyricsgenius
genius = lyricsgenius.Genius(token) |
11,075 | 9c64e955e344307960a69fc2d0335335b5698760 | import gym
import torch
import numpy as np
import torchvision.transforms as T
import matplotlib.pyplot as plt
from IPython import display as ipythondisplay
class CartPoleEnvManager():
def __init__(self, device, env_wrapper=lambda x: x, timestep_limit = 100, xvfb_mode=False):
self.device = device
env = gym.make('C... |
11,076 | 02c4131a1a645489929cf87048db43c3b074e938 | """KERNEL SVM"""
from sklearn.svm import SVC
classifier4 = SVC(kernel = 'rbf', random_state = 0)
classifier4.fit(X_train, y_train)
y_pred4 = classifier.predict(X_test)
print(np.concatenate((y_pred4.reshape(len(y_pred4),1), y_test.reshape(len(y_test),1)),1))
from sklearn.metrics import confusion_matrix, accuracy_scor... |
11,077 | 5106da050825a85069464e4267d9f3b48c49b628 | from django.contrib import admin
from models import Message,Notification,Detail,Location, Organization, Account, Profile, Action
admin.site.register(Message)
admin.site.register(Notification)
admin.site.register(Detail)
class LocationAdmin(admin.ModelAdmin):
fields = ['place', 'postalcode', 'address', 'county'... |
11,078 | a9f67dffdfba590ec804b97cc08f86bcfc6c0a27 | import base64
img_data = b"<base64 here>"
with open("imageToSave.jpg", "wb") as fh:
fh.write(base64.decodebytes(img_data))
|
11,079 | 47efe60073d3773351dfc014db15705407daedf0 | from enum import Enum
class ExitStatus(Enum):
SUCCESS = 0
FAILURE = 1
def reportStatusAndExit(errorCount, checkPrefix):
exitStatus = ExitStatus.SUCCESS
if errorCount > 0:
exitStatus = ExitStatus.FAILURE
print (f'{checkPrefix} {exitStatus.name}\n')
exit(exitStatus.value)
|
11,080 | 70be91e52d55c099adf3dc4f9609a906782b965b | #倒序删除
#因为列表总是‘向前移’,所以可以倒序遍历,即使后面的元素被修改了,还没有被遍历的元素和其坐标
#还是保持不变的
a=[1,2,3,4,5,6,7,8]
print(id(a))
for i in range(len(a)-1,-1,-1):
if a[i]>5:
pass
else:
a.remove(a[i])
print(id(a))
print('-----------')
print(a) |
11,081 | 8294c6b2645cd92f6e445c54b59c76795074d505 | import time
import traceback
import django.core.mail
from constance import config
from django.conf import settings
from django.core import management
from django.db import transaction
from django.utils import translation
from polygon_client import Polygon, PolygonRequestFailedException
from modules.polygon import mod... |
11,082 | fe093191102e2fab3d8b2d461b7807208f33674f | """
This example implements the experiments on citation networks from the paper:
Semi-Supervised Classification with Graph Convolutional Networks (https://arxiv.org/abs/1609.02907)
Thomas N. Kipf, Max Welling
using the convolutional layers described in:
Convolutional Neural Networks on Graphs with Fast Localized Spe... |
11,083 | 5a439040e3c8a04b0f05663539aa0f68ffa81404 | import pandas as pd
from abc import *
from tqdm.auto import tqdm
class AbstractRecommend(metaclass=ABCMeta):
def __init__(self):
pass
@abstractmethod
def recommend(self):
pass
def calculate_recommend(self, frame, before_recommend_count, cutoff_recommend_count):
... |
11,084 | ab3678938de30d32401f44444ae5381121e5dcac | import re
"""
First Task
"""
# Initial Persons
persons_list = []
for index in range(1, 4):
print(f"Person number {index}:")
person = {
'name': input('Enter your name\n'),
'age': int(input('Enter your age\n'))
}
persons_list.append(person)
# 1)
for person in persons_list:
if pe... |
11,085 | d55d4ca4f4ed3732620bcfa059ae85af6689b919 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import reverse, render, HttpResponseRedirect, get_object_or_404,HttpResponse
import json
from .models import Device, Log
import logging
from django.contrib import messages
logger = logging.getLogger('stable')
# Create your views he... |
11,086 | a9b1302769e974f48fc6128b8579002440ad0408 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-05-22 13:08
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('seats', '0026_auto_20180510_1801'),
]
operations = [
migrations.AlterModelOptions(
... |
11,087 | a62f2877e6e702b13e237e67b2dda7ee52feb89c | # CodeUp #1116
a, b = map(int, input().split())
print('%d+%d=%d' %(a, b, a+b))
print('%d-%d=%d' %(a, b, a-b))
print('%d*%d=%d' %(a, b, a*b))
print('%d/%d=%d' %(a, b, a/b))
print('{}+{}={}'.format(a, b, a+b))
print('{2}-{1}={0}'.format(a-b, b, a))
print('{}*{}={}'.format(a, b, a*b))
print('{}/{}={}'.format(a, b, int(a... |
11,088 | 36c6f865856bd5d3c25e84e9c04c8d2d24d72ac9 | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http.response import HttpResponse
from .models import Candidate
# Create your views here.
def index(request):
candidates = Candidate.objects.all()
context = {'candidates':candidates}
return render(request,'elections/index.html', con... |
11,089 | 7d872eee093f2ba481356929c29a4aa924e314e1 | from decorator_include import decorator_include
from django.conf import settings
from django.conf.urls.i18n import i18n_patterns
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from django.urls import include, path, re_path
from django.views import defaults
from django.vie... |
11,090 | 86b4616bd8ba70f65b542cf7c7101188a189c78f | class Solution:
def concatenatedBinary(self, n: int) -> int:
binString = ""
for i in range(n + 1):
binString = binString + "{0:b}".format(i)
return int(binString, 2) % 1000000007
|
11,091 | 323360bc3cce94146c0cb84be0a1b8c8205a308a | from django.conf.urls import url
from django.urls import path
from Blogs import views
urlpatterns = [
path('blog_posts.html', views.blog_posts, name='blog_posts'),
path('blog_form.html', views.blog_post_form, name='blog_post_form'),
] |
11,092 | fd9f1180c8f16f9b280f7a539a6d734926645ab2 | ########################
# Author: ~wy
# Date: 25/12/2017
# Description: Represents one of the 6 Guesses in the game
########################
class Guess:
def __init__(self, choices):
self.choices = choices
def get_choices(self):
return self.choices
def __str__(self):
return "[{... |
11,093 | 0b97bad2fc0adf54957ed3cbb269590a3e8dde04 | height=input("Please enter your height in meter")
weight=input("please enter your weight in kg")
f_height=float(height)
f_weight=float(weight)
print(f_weight/(f_height**f_height)) |
11,094 | 28923379dc03a7742df5c0604c23abbd9c3b025f | import OpenSSL , ssl, argparse ,json, os.path, validators, requests, logging
from datetime import datetime
from dateutil.parser import parse
from urllib.parse import urljoin
from akamai.edgegrid import EdgeGridAuth, EdgeRc
from pathlib import Path
#TODO: FIX logger format
#turn off logger
#send ouput to tmp file
#imp... |
11,095 | fbffe98481625d15b92767f836673c19e2b1e9a6 | import re
from rest_framework import serializers
from django.contrib.auth import get_user_model, authenticate
from django.contrib.auth.models import update_last_login
from django.utils.translation import gettext as _
from rest_framework_jwt.settings import api_settings
from wallet.serializers import WalletSerializer
... |
11,096 | e38b7dc98a9ff5e334cdb7562987d61df60cf7c5 | '''
Created on Sep 5, 2019
@author: achaturvedi
'''
answer = 17
if answer != 42:
print("That is not the correct answer. Please try again") |
11,097 | 9f1fcb0ef36447c490f5a436d7827caf75bcb832 | def gcdEuclidAdv(m,n):
if m>n:
(m,n)=(n,m)
if(m%n) == 0:
return n;
else:
return gcdEuclidAdv(n,m%n)
m = int (input("Enter m value : "))
n = int (input("Enter n value : "))
print(gcdEuclidAdv(m,n)) |
11,098 | 2d09b9d26c9f7ef5ff786061e6b3b6eb7e2d20fc | km_percorridos=float(input("Digite os kilometros percorridos: "))
dias_alugado=int(input("Quantidade de dias que o carro foi alugado: "))
aluguel=dias_alugado*60
valor_km=km_percorridos*0.15
total_aluguel=aluguel+valor_km
print("O valor a pagar por dias locado fica R$%5.2f e o valor pela quantidade de Km rodados fica R... |
11,099 | ffda8c77c2895d334472eb1cfb8f2cedc0e9d4ab | # Напишите программу, которая обрабатывает результаты IQ-теста из файла “2-in.txt".
# В файле лежат несколько строк со значениями(не менее 4-х).
# Программа должна вывести в консоль среднее арифметическое по лучшим трем в каждой строке результатам(одно число).
a = []
n = []
t = True
f = open('2-in.txt')
for line... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.