text stringlengths 8 6.05M |
|---|
# Generated by Django 3.2.9 on 2021-11-17 09:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bookapi', '0002_auto_20211116_1538'),
]
operations = [
migrations.AlterField(
model_name='book',
name='nome',
... |
from django.db import models
from multiselectfield import MultiSelectField
from GlobalModels.models import Skills, Tools, Field_of_work
# Create your models here.
class Job(models.Model):
headline = models.CharField(max_length=255)
description = models.CharField(max_length=255, blank=True)
locati... |
#!/usr/bin/env python
# coding: utf-8
# # Chapter 5 - Material properties
# In[1]:
get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plt
import numpy as np
import csv
# ## The dihedral angle
#
# An equation for dihedral angle $\Theta$ is
#
# $$
# \begin{equation}
# \label{eq:di... |
from socket import *
BUFSIZ = 1024
HOST = input('host:')
PORT = input('port:')
if not HOST:
HOST = 'localhost'
if not PORT:
PORT = 21567
PORT = int(PORT)
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
data = input('> ')
if not data:
break
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 21 21:50:46 2019
@author: standl
"""
import memory_process
import sys
import math
import numpy as np
def check_free(m_table, process_id, size):
cont_free = 0
max_cont = 0
total_free = 0
consecutive = 0
fit = 0
start = []
en... |
import random
import math
import matplotlib.pyplot as plt
from collections import defaultdict, Counter
def random_kid():
return random.choice(["boy", "girl"])
both_girls = 0
older_girl = 0
either_girl = 0
random.seed(0)
for __ in range (10000):
younger = random_kid()
older = random_kid()
if older ==... |
import os
import json
import pickle
from random import sample
ESTILO = (("label_principal", "background-image: url(gui/logo.png);"),
("boton_serializar", "background-image: url(gui/guantlet.png);"),
("boton_deserializar", "background-image: url(gui/dragon_balls.png);"),
("label_personas"... |
# グラフ関係
def autocorrelation(data, h):
"""
系列相関を計算
Parameters
--------------
data : ndarray
時系列データ
h : int
時点差
Returns
---------
r : double
系列相関
"""
length = len(data)
data_front = data[:length - h]
data_back = data[h:] # 前半データと後半デ... |
import logging
import subprocess
def run_shell_command(command, charset='utf-8'):
output = subprocess.check_output(command, shell=True)
# Swallow *all* errors from logging. We really don't want to interrupt flow just because logging fails.
# noinspection PyBroadException
try:
logging.info('ou... |
def solution(n):
n = int(n)
num_steps = 0
while n > 1:
if n % 2 == 0:
n = n >> 1
elif (n == 3) or (n % 4 == 1):
n = n - 1
else:
n = n + 1
num_steps += 1
return num_steps
print(solution('15')) # 5
print(solution('4')) # 2 |
#!/usr/bin/python
## -*- coding: utf-8 -*-
#
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import json
import cgi
import sqlite3
import aml_pwpw_gexp
import aml_pwpw_clin
import aml_pwpw_drug
import aml_pwpw_gsva
qform = cgi.FieldStorage()
source = qform.getvalue('insource')
#source = "gsva"#sys.argv[1]
# 'can... |
#!/usr/bin/env python3
#
# Run a test. Just the test spec is provided on stdin.
#
from pysnmp.hlapi import *
import pysnmp
import datetime
import json
import re
import sys
import time
import pscheduler
log = pscheduler.Log(prefix="tool-pysnmp", quiet=True)
# check for missing required fields
def missing_input(spec,... |
#!/usr/bin/env python
import sys,os
sys.path.insert(1,'../../')
import numpy as np
import pylab as py
import tools
from tools import tex,plot_band,fill_between
import lhapdf
import matplotlib.gridspec as gridspec
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Times-Roman']})
rc('text',uset... |
def intersection(nums1, nums2):
lookup = set()
ret = []
for num in nums1:
lookup.add(num)
for num in nums2:
if num in lookup:
ret.append(num)
lookup.discard(num)
return ret |
import gtk
import config
import pulseBeam
import spectrum_loader
class AddElement_Dialog:
def __init__(self,add_callback):
self.add_callback = add_callback
#create window
self.window = gtk.Window()
self.window.connect("destroy", self.close_window)
s... |
from .models import Comment
from django import forms
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['body']
def __init__(self, *args, **kwargs):
''' Labels removed from body field on comment form
[Code taken from 'https://stackoverflow.com/questions/... |
# -*- coding: utf-8 -*-
# @Author: Li Qin
# @Date: 2019-12-02 12:44:58
# @Last Modified by: Li Qin
# @Last Modified time: 2019-12-02 12:52:41
from flask import jsonify
def response_success(content={'success':'success'}):
response = jsonify(content)
response.status_code = 200
return response
def respo... |
from abc import ABCMeta, abstractmethod
from typing import List, Union
from api.api_repository.AddressRepository import AddressRepository
from api.models import Address
from api.api_dto.AddressDto import *
class AddressManagementService(metaclass=ABCMeta):
@abstractmethod
def create_address(self, model: Crea... |
n=1000-int(input())
money=[500,100,50,10,5,1]
cnt=0
for i in money:
cnt+=n//i
n%=i
print(cnt) |
#!/usr/bin/python
#\file follow_q_traj2.py
#\brief Follow a joint angle trajectory.
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Nov.21, 2019
#Based on: ../ur/follow_q_traj2.py
import roslib
import rospy
import actionlib
import control_msgs.msg
import trajectory_msgs.msg
import time, mat... |
import similarity
def func(a,c):
for i,v in a:
if i in c:
print i,v
dao = similarity.new_DAO_interface()
a=dao.get_item_list_by_user(44)
b=dao.get_item_list_by_user(572)
i = set([i for i,v in a]) & set([i for i,v in b])
func(a,i)
print "fuck"
func(b,i)
print similarity.similarity_func(a,b,1682... |
from onegov.core.security import Public, Private, Personal
from onegov.org.forms.resource import AllResourcesExportForm
from onegov.org.views.resource import (
view_resources, view_find_your_spot, get_room_form,
get_daypass_form, handle_new_room, handle_new_daypass,
get_resource_form, handle_edit_resource,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'bpmacmini01'
# # 多线程
import time, threading
#
#
# def loop():
# print('thread %s is running...' % threading.current_thread().name)
# n = 0
# while n < 5:
# n += 1
# print(('thread %s >>> %s' % (threading.current_thread().name, n... |
x = int(input('Enter the number want to test for prime factors: '))
#Generate Factors
factors = []
for i in range(2,x+1):
if not x % i:
factors.append(i)
#Test Factors as Primes
for n in factors:
if n > 4:
for z in range( 3,n):
if n % z:
continue
factors... |
# -*- coding:utf-8 -*-
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
res = []
self.tb(1,n+1,k,[],res)
return res
def tb(self, c, n, k, tlist, res):
if k==0:
res.appen... |
# coding=utf-8
import urllib.parse
import sys
import urllib.request
import gzip
from bs4 import BeautifulSoup
# params CategoryId=808 CategoryType=SiteHome ItemListActionName=PostList PageIndex=3 ParentCategoryId=0 TotalPostCount=4000
def getHtml(url,values):
user_agent='Mozilla/5.0 (Windows NT 6.3; WOW64) AppleW... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 13 14:56:16 2018
@author: SHREE
"""
import pandas
from pandas.tools.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklea... |
import sys
sys.path.insert(0, '../src')
from functions import (fetch_data, parse_data, get_table_rows,
get_all_stocks_data, create_children_array, parse_stock_period, get_title_data, get_stock_pe_and_title)
globes_url = "https://www.globes.co.il/portal/quotes/?showAll=true#jt266"
one_stock_url = "https://www.bizpor... |
import bpy
import random
import copy
def createMesh(name, origin, verts, edges, faces):
# Create mesh and object
me = bpy.data.meshes.new(name+'Mesh')
ob = bpy.data.objects.new(name, me)
ob.location = origin
ob.show_name = True
# Link object to scene
bpy.context.scene.objects.link(ob)
... |
a = type("Bangladesh")
print(a,'Bangladesh')
# # country = "Bangladesh"
# # print(country)
# # print(len[country])
# list = ['mehedi','mona',10,]
# print(len(list))
# country = ['Bangladesh']
# print(list.find('Bangladesh'))
|
from django import template
from django.urls import reverse
try:
from django.db.models.loading import get_model
except ImportError:
from django.apps import apps
get_model = apps.get_model
from django.template import TemplateSyntaxError
from django.utils.functional import wraps
from django.utils.translati... |
class CreateDestinationDto:
id: int
location: str
description: str
journey: str
class ListDestinationDto:
location: str
description: str
journey: str
class DestinationDetailsDto:
id: int
location: str
description: str
journey: str
class EditDestination:
location: ... |
from som.vm.universe import error_print, error_println
def dump(clazz):
for inv in clazz.get_instance_invokables_for_disassembler():
# output header and skip if the Invokable is a Primitive
error_print(str(clazz.get_name()) + ">>" + str(inv.get_signature()) + " = ")
if inv.is_primitive():... |
import shelve
import uuid
import os
import io
class File:
def Upload(self,nama=None,data=None):
f=open("server/"+nama, "wb")
f.write(data)
f.close()
return True
def Download(self,nama=None):
if os.path.isfile("server/"+nama):
myfile = open("server/"+nama, "r... |
# Generated by Django 2.2.5 on 2020-06-25 11:02
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('account', '0004_auto_20200624_0850'),
]
operations = [
migrations.RemoveField(
model_name='profile',
name='fir... |
# Curso em Vídeo Lesson 08
# https://www.youtube.com/watch?v=oOUyhGNib2Q&list=PLHz_AreHm4dlKP6QQCekuIPky1CiwmdI6&index=24
# Importing the whole library
import math
num = int(input('Type an integer: '))
root = math.sqrt(num)
print('The root of the number {} is {}'.format(num, root))
# Rounding the root
# ceil() rou... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# The above lines tell the shell to use python as interpreter when the
# script is called directly, and that this file uses utf-8 encoding,
# because of the country specific letter in my surname.
'''
Name: Program 3
Author: Martin Bo Kristensen Grønholdt.
Version: 1.0 (2016... |
import subprocess
def cpp_open(fp='C:/Users/Gerst/Documents/GitHub/Math-Programming/Python/ProbabilitySim/CF.exe ',args= '1 2 15000'):
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
p = subprocess.Popen(fp+args, startupinfo=startupinfo,stdout=subprocess.PIPE)
... |
import webapp2
from Handler import Handler
from NewPostPage import NewPost
from PostPage import PostPage
from EditPost import EditPost
from DeletePost import DeletePost
from NewComment import NewComment
from EditComment import EditComment
from DeleteComment import DeleteComment
from SignUpPage import SignUpPage
from ... |
from state_stack import StateStack
from state import State
class StoryboardEvent:
def __init__(self, factory):
self.factory = factory
self.event = None
def update(self, storyboard, dt):
if self.event is None:
self.event = self.factory(storyboard)
self.event.update(... |
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from .managers import MyUserManager
class MyUser(AbstractUser):
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ['password']
email = models.EmailField(_('email address'), unique=Tru... |
import pandas as pd # Version 0.21.0
import matplotlib
from datetime import timedelta
matplotlib.use('Agg') # Force matplotlib to not use any Xwindows backend.
from matplotlib import pyplot as plt
filename = 'btcbot.log'
df = pd.read_json(filename, lines=True)[-2*24*60*60/3:]
date = pd.to_datetime(df['date'], format=... |
import sys
import time
from process_exec.exec_cmd_managed import ExecCmdManaged
from third_party.kbhit import KBHit
if __name__ == "__main__":
cmd_managed = ExecCmdManaged(["sudo", "-S", "sh"])
# cmd_managed = ExecCmdManaged(["sh"])
cmd_managed()
stdout_inst = cmd_managed.create_stdout_subscription... |
from django.shortcuts import redirect, render
from .models import * # importing luggage data class
from django.http import JsonResponse
from .blockchain.blockchain import *
from django.contrib.auth.models import User, auth
from django.contrib import messages #for showing messages either errors or others on html page ... |
#!/usr/bin/env python
# encoding: utf-8
# 2016.11.8 17:21 by drop 342737268(qq)
import re
import os
import sys
import csv
import time
import operator
import itertools
COMPAT = False
if '2.7' in sys.version:
COMPAT = True
def get_module(modules):
""":modules: list, install module list"""
for i in modules... |
import html_downloader
import html_outputer
from Utils import get_md5
class SpiderMain(object):
def __init__(self, path):
self.downloader = html_downloader.HtmlDownloader(path)
self.outputer = html_outputer.HtmlOutputer()
def crawl(self, root_url, parents_url=None):
current_url, data... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 3 11:05:03 2019
@author: zhihuan
"""
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.autograd import Variable
from torch import optim
import numpy as np
import math, random
import pandas as pd
import utils
from ... |
import numpy
import cv2
img= cv2.imread('../img/123.jpg')
b = img [:,:,0]
print(b)
g= img [:,:,1]
print(g)
r= img [:,:,2]
print(r)
cv2.imshow('blue',b)
cv2.imshow('green',g)
cv2.imshow('red',r)
cv2.waitKey(0)
cv2.destroyAllWindows() |
# -*- coding: utf-8 -*-
from django.conf.urls import url
from projects import views
urlpatterns = (
url(
r'^(?P<lang>\w{2})/projects/$',
views.ProjectsIndexView.as_view(), name='projects_index'
),
url(
r'^(?P<lang>\w{2})/projects/page/(?P<page>[0-9]{1,4})/$',
views.Project... |
# Generated by Django 3.0.5 on 2020-06-18 04:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0006_auto_20200618_0428'),
]
operations = [
migrations.AlterField(
model_name='rentoffer',
name='latitude',
... |
from django import forms
from creditcards.forms import CardNumberField, CardExpiryField, SecurityCodeField
from .models import CreditCard
class AddCreditCard(forms.ModelForm):
cc_name = forms.CharField(label='Name on Card')
cc_number = CardNumberField(label='Card Number')
cc_expiry = CardExpiryField(label... |
import numpy as np
# backpropagation
##############################################################
def backprop_1d_to_1d(delta, prev_weights, prev_activations, z_vals, final=False):
if not final: # reset delta
sp = sigmoid_prime(z_vals)
# print 'w,d,z_vals: ', prev_weights.shape, delta.shape, sp... |
''' # perhap pdf, word
for document in documents:
print document.name + ': ' + document.show()
'''
#!/usr/bin/env
############################################
# document.py
# Author: Paul Yang
# Date: June, 2016
# Brief: this is to show HOWTO of python class, __init__method, accessing instance/class attribute ... |
import csv
import matplotlib.pyplot as plt
from math import log
import pandas as pd
def read_t_1():
fix = []
for i in range(1,10):
f = i/10
with open('data t '+str(f)+' and r0.csv', 'r') as csvnew:
read = csv.reader(csvnew)
for line in read:
fix.append(li... |
"""Dumps numbers from 0 to 9 into the json file"""
import json
def json_dump_ej(filename):
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
with open(filename, 'w') as file:
json.dump(numbers, file)
|
'''
This script creates a to_run.sh file which is to
be run using pool.py.
Let's say you're running a python script named
training.py, and it accepts several flags (e.g.
--lr, --attr). You could write something like
with open("to_run.sh", "w") as to_run
for lr in [0.01, 0.001]:
for attr in range(40):
... |
def divideByZero(numerator, denominator):
try:
return numerator/denominator
except:
print('denominator is Zero. Cannot divide an number by 0')
print( divideByZero(100, 10) )
print( divideByZero(numerator=200, denominator=0) )
print( divideByZero(denominator=200, numerator=0) )
|
"""OpenTaal lexicon ingestion."""
import os.path
import pandas as pd
from ..dbutils import add_lexicon, session_scope
def ingest(session_maker, base_dir='',
opentaal_file='OpenTaal/OpenTaal-210G-BasisEnFlexies.txt', **kwargs):
"""Ingest OpenTaal lexicon into TICCLAT database."""
wfs = pd.read_csv(... |
def selectionSort(arr):
tracker = 0
len_ = len(arr)+1
returnArray = list()
while tracker <= len_:
min_ = min(arr)
returnArray.append(min_)
del arr[arr.index(min_)]
tracker += 1
len_ -= 1
returnArray.append(arr[0])
return returnArra... |
def prime(n): # int :=> bool
if n == 2: return True
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0: return False
return True
if __name__ == '__main__':
primes = [3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511]
print(all([prime(n) for n in primes])) # True |
import json
# from keras import metrics
from keras.optimizers import Adam
from keras.callbacks import EarlyStopping, ModelCheckpoint
from time import strftime
def train_model(model, X_train, y_train, X_val, y_val, epochs=200):
# model = simple_lstm.get_model()
# model.summary()
# 20190701 clipnorm 1.->0.01... |
a = 1
b = 2
print("1 + 2 ")
print(a + b)
nome = "Paula"
print("O nome é : ")
print (nome)
|
"""
Library for representing 7shifts Users.
"""
from . import base
from . import exceptions
ENDPOINT = '/v2/company/{company_id}/users'
def get_user(client, company_id, user_id, **urlopen_kw):
"""Implements the 'Read' API in 7Shifts for the given `user_id`.
Returns a :class:`User` object, or raises
:clas... |
#!/usr/bin/env python
# encoding: utf-8
"""
based on "Staircase.py"
Created by Tomas HJ Knapen on 2009-11-26.
Copyright (c) 2009 TK. All rights reserved.
Adapted for this package by Gilles de Hollander
2017-08-17
"""
import numpy as np
# import matplotlib.pylab as pl
class OneUpOneDownStaircase(object):
"""
OneUpO... |
# https://www.tptp.org/TPTP/TPTPTParty/2007/PositionStatements/GeoffSutcliffe_SZS.html
import re
from contextlib import suppress
short_to_long = {
# Unsatisfiable
'THM': 'Theorem',
'CAX': 'ContradictoryAxioms',
'UNS': 'Unsatisfiable',
# Satisfiable
'SAT': 'Satisfiable',
'CSA': 'CounterSati... |
from locking import data, sanity
import numpy as np
data.EFishes().populate(reserve_jobs=True)
data.Cells().populate(reserve_jobs=True)
data.FICurves().populate(reserve_jobs=True)
data.ISIHistograms().populate(reserve_jobs=True)
data.Baseline().populate(reserve_jobs=True)
data.Runs().populate(reserve_jobs=True)
data.G... |
import numpy as np
import serial
import time
import cv2
from math import *
# All params are in m. Calculation are done for our setup, may vary.
# Distance of screen from camera = D
D=1.46
# Height of the camera = H
H= 0.70
# Height of the nozzle = h
h=0.21
# Distance of the nozzle from screen
d=0... |
import pygame
import random
def main():
WIDTH = 3000
HEIGHT = 1000
WHITE = (255, 255, 255)
starting_point = (WIDTH // 2, HEIGHT // 2)
positions = [starting_point]
separation = int(input('Type the separation between dots(int):'))
pygame.init()
while True:
# To close the g... |
# Copyright 2016 Jochen Kursawe. See the LICENSE file at the top-level directory
# of this distribution and at https://github.com/kursawe/MCSTracker/blob/master/LICENSE.
import mesh
import tracking
import copy
import matplotlib as mpl
import matplotlib.pyplot as plt
from os import path
from os.path import dirname
imp... |
# -*- mode:python; coding:utf-8; tab-width:4 -*-
import Ice
Ice.loadSlice('-I {} cannon.ice'.format(Ice.getSliceDir()))
import Cannon
import numpy as np
from common import M1, M2, M3, M4, M6, M8
import math
import itertools
def list_split(list, parts):
x=np.array(list)
list=np.array(np.split(x,parts))
return lis... |
class StudentMarks:
def __init__(self, stdname, marks):
self.stdname = stdname
self.marks = marks
def agerage(self):
avg = sum(self.marks)/len(self.marks)
print("the average of student: ", self.stdname, " is ", avg)
std1 = StudentMarks("Jayesh", [60,90,70,80,100])
print(std1.... |
# Generated by Django 3.2.5 on 2023-03-29 20:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('share', '0061_ensure_auto_users'),
]
operations = [
migrations.CreateModel(
name='IndexBackfill',
fields=[
... |
print("wadidaww")
print("hallo bernino") |
#!/usr/bin/env python
from flup.server.fcgi import WSGIServer
from server import app
if __name__ == '__main__':
WSGIServer(app, bindAddress='/tmp/sms-fixer-fcgi.sock', umask=0002).run()
|
from animal import Animal
#创建子类时,父类必须包含在当前文件中,且位于子类前面 在子类括号指定父类名称
class Dog(Animal):
"""docstring for ClassName"""
def __init__(self, name, age):
"""初始化父类属性"""
super().__init__(name,age)
self.tail = "yellow"
def roll_over(self):
"""模拟小狗打滚"""
print(self.name.title()+" ... |
from ED6ScenarioHelper import *
def main():
# 玛诺利亚间道
CreateScenaFile(
FileName = 'R2101 ._SN',
MapName = 'Ruan',
Location = 'R2101.x',
MapIndex = 100,
MapDefaultBGM = "ed60020",
Flags = 0,
... |
'''
Write a function that returns a possible alphabet given a sorted list of strings
Input: ["ct", "bt", "tb"]
Output: ['c', 'b', 't']
Input: ["cc", "cb", "bb", "ac"]
Output: ['c', 'b', 'a']
Counter example: assigning each character a rank
input: ["cb", "cg", "db", "dx", "dg", "bg"]
output: ['c', 'd', 'b', 'x', 'g']
... |
# This is a script for running the complete 2d-stitching of SEM images based on
# Rhoana's rh_aligner[https://github.com/Rhoana/rh_aligner].
# We modified it to run on local machine(not cluster) and support single-beam file structure.
# Raw Author: Harvard VCG Group, Rhoana Project[https://github.com/Rhoana]
# Author:... |
import asyncio
import datetime
import re
import urllib.request
from bs4 import BeautifulSoup
import discord
from setting import token
def list_to_str(list, option=""):
str = ""
for i in list:
str += i + option
return str
def _time(when="now"):
KST = datetime.timedelta(hours=9)
if when ==... |
from OrderCollection import OrderCollection
myord = OrderCollection([
{'name':'tyler', 'otherprop':1},
{'size':'m','name':'sarah'}
])
filteredOrders = myord.getPeopleWhoOrdered({
'name':'sarah',
... |
from numpy import *
from scipy.special import erf
def makeN( x ):
n = len(x)
N = zeros((n,n))
N[:,0]=1.
for j in range(1,n):
N[:,j]=N[:,j-1]*(x-x[j-1])
return N
def evalpoly(xdata,c,x):
e = ones_like(x)
p = zeros_like(x)
for i in range(len(xdata)):
p += c[i]*e
e ... |
"""
Author:Rawley Collins
Program: update_scores_dict.py
"""
MIN = 0
MAX = 100
def get_test_scores():
scores_dict = dict()
try:
num_scores = int(input("How many scores would you like to enter: "))
if MIN > num_scores:
raise ValueError
except ValueError:
raise ValueError
for num in range(num_scores):
... |
import cv2
# ---------------------draw line----------------
img = cv2.imread('C:\\fakepath\\hackathon.png', 1)
# param:
# - image object
# - tuple coordinates of p1 (start) x1,y1
# - tuple coordinates of p2 (end) x2,y2
# - color in bgr (b,g,r). Blue is (255,0,0)
# - thickness (numbers)
img = cv2.line(... |
#!/usr/bin/env python3
# To invoke this script in neomutt with a message selected
# 1) add the following macro to neomuttrc:
#
# macro index,pager Ce ";<pipe-message>inbasket<enter>" "pipe to inbasket"
#
# 2) install this script somewhere in your path as "inbasket"
# and make it executable (chmod +x inbasket).
impor... |
from collections import defaultdict
import chainer
import chainer.functions as F
import chainer.links as L
import numpy as np
from graph_learning.dataset.crf_pact_structure import CRFPackageStructure
from graph_learning.model.open_crf.cython.factor_graph import FactorGraph
from graph_learning.model.open_crf.cython.op... |
import time
import game_utilities
def inventory_main(player, game_data):
sorted_list = sort_alphabetically(player.inventory)
# ways to sort: Alpha, Numer, Type, Recent
# Adjust strings for name, amount, type
# create list of strings to print
show_inventory(sorted_list)
# Management Loop
de... |
#!/usr/bin/env python3
langs = {"Perl", "Python", "Java", "Go", "C++", "Rust"}
bad_langs = {"Perl", "C++"}
print(langs.difference(bad_langs))
new_langs = {"Rust", "Go", "Dart"}
print(langs.intersection(new_langs))
cool_langs ={"Go", "Python"}
print(cool_langs.issubset(langs))
|
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
#
# Scope: Master per protocollo Ln-Rs485
# Invia il comando sul Relay collegato sulla porta seriale
# Il Relay ritrasmette il comando sul bus Rs485
#
# updated by ...: Loreto Notarantonio
# Version ......: 23-01-2018 16.58.39
#
# #########################... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 25 22:01:56 2018
@author: Mauro
"""
#==============================================================================
# Imports
#==============================================================================
# py imports
import datetime
from tkinter import Label, Toplevel
... |
import logging
log = logging.getLogger('onegov.town')
log.addHandler(logging.NullHandler())
from onegov.town6.i18n import _
from onegov.town6.app import TownApp
__all__ = ['_', 'log', 'TownApp']
|
# -*- coding: utf-8 -*-
__author__ = 'Yuvv'
import functools
def fun4filter(rule, tgt, conditions):
if rule[-3] == tgt:
if rule[0] == '&':
for cdt in rule[1:-3]:
if cdt[0] not in conditions:
return False
elif rule[0] == '|':
for cdt in ... |
import sys
import boto
timestamp = sys.argv[1]
master = 'salt-master-%s' % timestamp
minion = 'salt-minion-%s' % timestamp
autoscale = boto.connect_autoscale()
ec2 = boto.connect_ec2()
autoscale.delete_auto_scaling_group(master, force_delete=True)
autoscale.delete_auto_scaling_group(minion, force_delete=True)
autosc... |
# -*- coding: utf-8 -*-
"""
This script reads the Coalesce version from the Coalesce POM file and
transforms it into a Python variable, so that it can be imported to other
scripts in the package ("setup.py", and "docs/source/conf.py" for the
documentation). It also stores authorship and copyright data.
Note ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2010 Francesco Piccinno
#
# Author: Francesco Piccinno <stack.box@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; eith... |
from bs4 import BeautifulSoup
import requests
from pathlib import Path
import os
import json
from google.cloud import bigquery
####################################################################################################
# This part parses all of the repo names that we have in our ground truth file (IE all the ... |
import cv2
import json
import numpy as np
import time
import csv
import os
import sys
from datetime import datetime
import matplotlib.pyplot as plt
if len(sys.argv) != 2:
print "Please provide the folder name as an argument"
else:
data = sys.argv[1]
if not os.path.exists(data + '/out/'):
os.makedirs(data ... |
from rest_framework import viewsets
from api.sourceconfigs.serializers import SourceConfigSerializer
from api.base import ShareViewSet
from share.models import SourceConfig
class SourceConfigViewSet(ShareViewSet, viewsets.ReadOnlyModelViewSet):
serializer_class = SourceConfigSerializer
ordering = ('id', )
... |
#!/usr/bin/python3
for x in range(ord('a'), ord('z')+1):
if (x != ord('e') and x != ord('q')):
print('{}'.format(chr(x)), end="")
|
"""
Time/Space Complexity = O(N)
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1 or not l2:
... |
import requests
def test_return_201_when_warehouse_is_created():
url="http://localhost:5000/create_warehouse"
data={'wh_ref':'Bodega-123456'}
r=requests.post(url,json=data)
assert r.status_code==201
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.