text stringlengths 38 1.54M |
|---|
import pygame
"""
Provides a bunch of name references for the custom
pygame events used in this game
Available Name Space = 25 - 31
"""
SURFACE = 25 # Event dict: surf=pygame.Surface, pos=(x, y), z=int
"""Allows the systems to send surfaces to the Renderer to be displayed"""
PRINT_LINE = 26 # Event dict: mess... |
import cx_Oracle
conn = cx_Oracle.connect('system/orcl@127.0.0.1/orcl')
c = conn.cursor()
x = c.execute('select sysdate from dual')
x.fetchone()
c.close();
conn.colse |
# Create your views here.
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.core import urlresolvers
from django.shortcuts import get_object_or_404
from django.views.generic import DetailView,DeleteView
from django.views.generic.edit import CreateView,UpdateView
from django.h... |
#import all required libraries
from datetime import datetime
import re
import sqlite3 as sql
import itertools
# Variable for your data file
whatsapp_chat_data='WhatsAppChatwithDevOps&CloudBabies.txt'
#Variable to store unprocessed line of your data
#errorFile=
#pattern to match date and time
id=1
pattern='^([1-9]{1,2}... |
import os
import sys
import xml.etree.ElementTree as ET
import subprocess
import shutil
def main():
PRODUCT_FLAVOR = None
PROJECT_ROOT = None
if len(sys.argv) < 2 or not os.path.exists(sys.argv[1]):
print("Error: There is missing argument.")
sys.exit(1)
PROJECT_ROOT = sys.argv[1]
... |
import pytest
from polargraph import Polargraph
import env
# Immediate commands are interpreted quickly
CMD_SETPENWIDTH = 'C02,{pen_width},END'
CMD_SETMACHINESIZE = 'C24,{width},{height},END'
CMD_GETMACHINEDETAILS = 'C26,END'
# CMD_RESETEEPROM = 'C27,END'
CMD_SETMACHINEMMPERREV = 'C29,{mm_per_rev},END'
CMD_SETMACHINE... |
# Generated by Django 2.2.4 on 2019-08-19 23:35
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-07-30 23:19
from __future__ import unicode_literals
from django.db import migrations
import django_countries.fields
class Migration(migrations.Migration):
dependencies = [
('accounts', '0006_appuser_country'),
]
operations = [
... |
import os
def relative_path(*segments):
return os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', *segments)
|
from sqlwrapper import *
from Fetch_Current_Datetime import *
from collections import defaultdict
import json
def Query_Table_Status(request):
get_table_details = json.loads(dbget("select login_status.login_status,payment_type.*,table_status.table_status,\
table_deta... |
from common import TreeLinkNode
class Solution:
def connect(self, root):
if not root:
return None
p = [root]
while p:
res = []
for index, node in enumerate(p):
node.next = p[index + 1] if index + 1 < len(p) else None
if no... |
from PyQt5.QtWidgets import QTreeWidgetItem
class Ext_Item(QTreeWidgetItem):
def __init__(self, parent, id_item=None):
super(Ext_Item, self).__init__(parent)
self.id_item = id_item
|
import requests
# test HTTP GET method
response = requests.get('http://localhost:3000/')
print("response status code: " + str(response.status_code))
print("response body: " + response.text)
# test HTTP PUT method
response = requests.put('http://localhost:3000/', data={"param": "value"})
print("response status code: "... |
s = str(input())
if s.find("f") == -1:
exit()
if s.find("f") == s.rfind("f"):
print(s.find("f"))
else:
print(s.find("f"),s.rfind("f")) |
'''
Download random images using a sequential program
'''
import urllib.request
import time
import os
import threading
hosts = ["http://www.ox.ac.uk", "https://www.cam.ac.uk",
"http://www.canterbury.ac.nz", "http://www.lincoln.ac.nz",
"http://www.unitec.ac.nz", "http://www.victoria.ac.nz",
"... |
from tensorflow_utils import *
from tqdm import tqdm
import numpy as np
class DNN:
def __init__(self,no_hidden_layer,hidden_node_list,hidden_and_output_layer_activation_list):
self.no_hidden_layer = no_hidden_layer
self.hidden_and_output_layer_activation_list = hidden_and_output_layer_activation_list
self.h... |
"""
Django settings for cy project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths insid... |
#
# Sample Todo module
#
"""
Your license message ...
"""
import os, bottle, json, datetime
from appmodule import AppModule
from .modeldb import setupDB, Todo, MyS
class MyAppModule(AppModule):
def init(self):
DSN = self.module_config.get('DSN')
try:
setupDB(DSN)
except:
... |
#!/usr/bin/env python
from std_msgs.msg import Float32
from std_msgs.msg import Float32MultiArray
from my_first.msg import Num
import numpy as np
import rospy
import serial
W = 0.5 #distance between wheel bases
R = 0.125 #radius of the wheels
head = 0.1 #head recieved from the other node
vel_flag = 0
vl_ref = 45
vr_... |
import time
import json
import redis
import datetime
import requests
import traceback
import configparser
from . import privilege
from functools import wraps
from flask_cors import cross_origin
from flask import session, redirect, url_for, current_app, flash, Response, request, jsonify, abort
from ..model.login_model i... |
from py_helium_console_client import ConsoleClient
## See full documentation for the Console API: https://docs.helium.com/api/console/
API_KEY = 'PASTE_API_KEY_HERE'
# initialize client
client = ConsoleClient(api_key=API_KEY)
# list devices on account
devices = client.get_devices()
# search for a device by app key,... |
#!/bin/env python
import subprocess
import time
#import numpy as np
#dataWritingHistory=np.genfromtxt('userDefinedLog/dataWritingHistory',skip_header=0,delimiter=' ')
#with open('userDefinedLog/dataWritingHistory') as f:
# content = f.readlines()
def getTimes(fileName):
timeList = [line.rstrip('\n') for li... |
# to keep the main game seperate
import logging
log = logging.getLogger('run_cfg_game')
from cocos.director import director
from cocos.scene import Scene
import config
import constants
def loadandrun(args = None):
if constants.DEBUG:
gamename = config.gamefile
else:
gamename = ... |
import numpy as np
from sklearn.datasets import load_breast_cancer
class SVM(object):
def __init__(self):
self.b = 0
self.kernel = self.polynomial
self.gamma = 1
self.degree = 3
self.C = 1
def _ktt_violations(self, uy, alpha):
violations = np.zeros(len(uy))
... |
'''Problem
You just made a new friend at an international puzzle conference, and you asked for a way to keep in touch.
You found the following note slipped under your hotel room door the next day:
"Salutations, new friend!
I have replaced every digit of my phone number with its spelled-out uppercase
English repres... |
# import os
# from urllib.parse import urlparse
from tkinter import *
from pytube import YouTube
# filename_s = input("Please Enter Your File Name To Save:-")
root = Tk()
root.geometry('500x300')
root.resizable(0,0)
root.title("@MuL's video downloader")
Label(root,text = 'Youtube Video Downloader', font ='... |
from StringIO import StringIO
from unittest import TestCase
from rasmus.sexp import Sym
from rasmus.sexp import dict2sexp
from rasmus.sexp import parse
from rasmus.sexp import prepare
from rasmus.sexp import process
from rasmus.sexp import sexp2dict
from rasmus.sexp import write
from rasmus.sexp import write_pretty
... |
from environ import Env, Path
env = Env()
root = Path(__file__) - 2
BASE_DIR = root()
SECRET_KEY = env("SECRET_KEY")
DEBUG = env.bool("DEBUG", default=False)
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS", default=[])
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttyp... |
'''
Time O(N) | Space O(1)
'''
# 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: return l1 or l2
... |
import csv
import os
import urllib.request
import requests
import goodreads
import psycopg2
import json
res = requests.get("https://www.goodreads.com/book/review_counts.json", params={"key": "JHDKyR1QW0crrofMApghQ", "isbns": "9781632168146"})
print(res.json())
from flask import Flask, session, render_template, request... |
def stable_wall(R, C, rows):
res = []
graph = {}
in_degree = {}
res = ''
for i in range(R):
for j in range(C):
if rows[i][j] not in graph:
graph[rows[i][j]] = set()
if rows[i][j] not in in_degree:
in_degree[rows[i][j]] = 0
for c i... |
#!/usr/bin/env python3
# Quick Script to convert NVD information to CVE records
# Removed the need to store xml and zip files on the disk
# In[90]:
__author__ = "Quentin Mayo"
__copyright__ = "None"
__credits__ = ["Quentin Mayo"]
__license__ = "None"
__version__ = "1.0.0"
__maintainer__ = "Quentin Mayo"
__email__ =... |
# -*- coding: cp1252 -*-
import time
from scapy.all import *
#Declaration des variables
ipd = str(raw_input("Entrer une adresse IP: "))
portmin = str(raw_input("Entrer un port min: "))
portmax = str(raw_input("Entrer un port max : "))
ports = RandShort()
port = 0
ips = "10.101.200.13"
#Dictionnaire Port / services
... |
# Generated by Django 3.1.3 on 2021-04-11 03:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('talla', '0002_auto_20210410_2203'),
]
operations = [
migrations.AlterField(
model_name='talla',
name='eqv_letra',
... |
# Copyright (c) 2020 Leedehai. All rights reserved.
# Use of this source code is governed under the MIT LICENSE.txt file.
import argparse
import multiprocessing
import os
import sys
from enum import Enum
from typing import Any, Dict, OrderedDict, Tuple
from pylibs.score_utils import error_s
# Types.
Args = argparse... |
import numpy as np
#In order to reduce the computational cost of the particle filter and the trajectory generator, instead of reading every time through the whole
#MapFile as is extracted from its .csv file, it is more convenient to read only a particular region of interest. In this way, this script intends
# to extra... |
'''
Created on 31 Aug 2017
@author: Mathias Bucher
'''
class FileHandle(object):
'''
This class offers some methods for accessing files
in a sqlite database. It does not access the database
directly but offers methods to convert files into a
bytestream which can be stored in sql.
'''
sy... |
from __future__ import absolute_import, unicode_literals
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from scrapy_app.tasks import app as scrapy_app
__all__ = ('scrapy_app',)
|
"""
A monitor for a Port.
"""
class PortMonitor:
""" Looks at the number of items in the Port, in service + in the queue,
and records that info in the sizes[] list. The monitor looks at the port
at time intervals given by the distribution dist.
Parameters
----------
env: s... |
# -*- coding: utf-8 -*-
from openerp import fields, models, api
from dateutil.relativedelta import relativedelta
import json
from openerp.exceptions import UserError
class AccountInvoice(models.Model):
_inherit = "account.invoice"
@api.one
@api.depends('payment_move_line_ids.amount_residual')
def _get... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 23 12:41:03 2017
@author: elizabethheld
"""
## Import packages and dependencies
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model, decomposition, datasets
from sklearn.pipeline ... |
import mes_from_cpmd.ext_fortran.fortran_io as fio
from mes_from_cpmd.toolbox import CubeFileTools
from mes_from_cpmd.toolbox import transformations
from mes_from_cpmd.toolbox import lib_dme as lime
import ipdb
from mes_from_cpmd.misc import git_control
import mes_from_cpmd.toolbox.cube as cube
import numpy as np
impor... |
if __name__ == "__main__":
s = 'Hello from Python!'
words = s.split(' ')
print(words)
for w in words:
print(w)
for ch in s:
print(ch) |
from nltk.util import ngrams
def comment_length(comment, parent_traits):
return {'length': len(comment.body)}
def trigrams(comment, parent_traits):
traits = {}
for t in ngrams(comment.body, 3):
if t in parent_traits:
if 'shared_grams' in traits:
traits['shared_grams'] += 1
else:
traits['shared_gram... |
import csv
import requests
from urllib.parse import urlencode
import re
import os
import json
from hashlib import md5
from multiprocessing.pool import Pool
import time
def read_video(filename):
try:
url = []
with open(filename,'r',encoding='gbk') as csvfile:
reader = csv.reader(csvfile)... |
# Generated by Django 3.2.5 on 2021-07-09 12:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0007_auto_20210709_1738'),
]
operations = [
migrations.RemoveField(
model_name='boarding',
name='is_pet_dlv_b... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
import scipy.io
data=scipy.io.loadmat('ex3data1.mat')
Raw_X=data['X']
Raw_Y=data['y']
A=np.hstack((Raw_X,Raw_Y))
np.random.shuffle(A)
X=A[:,:399]
Y=A[:,400]
for i in range(5000):
if Y[i] == 10:
Y[i]=0
new_Y=n... |
from module import *
import torch
from torch import nn
from utils import *
EPOCH = 30
nIter = 1576
BATCH_SIZE = 10
LEARNING_RATE = 0.0001
vovab_size = len(word_counts)
# save training log
def write_txt(epoch, iteration, loss):
with open("/data/video-captioning/training_log.txt", 'a+') as f:
f.write("Epoc... |
from rest_framework import viewsets, status
from rest_framework.exceptions import NotFound
from rest_framework.response import Response
from authtoken.permissions import HasTokenScope
from foobar import api
from ..serializers.account import AccountQuerySerializer
from ..serializers.purchase import (
PurchaseSerial... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .musk import MUSK1, MUSK2
from .hastie import Hastie_10_2
|
from info2soft import config
from info2soft import https
class Summary (object):
def __init__(self, auth):
self.auth = auth
'''
* 获取总览列表
*
* @param dict $body 参数详见 API 手册
* @return list
'''
def listSummaryView(self, body):
url = '{0}/active/summary/list_... |
sep = ""
x = float(input("Enter x value : "))
if x > 0:
print("sign(",x,") = 1")
elif x < 0:
print("sign(",x,") = -1")
else:
print("sign(",x,") = 0")
|
# Import flask and template operators
from flask import Flask
app = Flask(__name__)
import server.controllers
|
from orm.models import Sensor, ExperimentSensor, Experiment
import datetime
from database_setup import trajectory_loader as tl
from database_setup import route_loader as rl
from database_setup import link_loader as lgl
from database_setup import taz_loader as tzl
import od_matrix_generator as od
import waypoint_od_matr... |
"""Main entry point for MARKS"""
import sys
if sys.argv[0].endswith("__main__.py"):
sys.argv[0] = "python -m marks"
from . import main
main.main(module=None)
|
from django.conf.urls import url, include
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
app_name = 'restMap'
urlpatterns = [
url(r'^counties/update/rema/$', views.updateRema, name='update_rema'),
url(r'^counties/update/kiwi/$', views.updateKiwi, name='update_kiwi'),
u... |
#等于 ==
a=3==4
print(a)
#不等于 !=
a=3!=4
print(a)
#其它符号 >,>=,<,<=
print("wangxiaojing">"liudana")
print("WangXiaoJing">"LiuDaNa")
c=3
c+=3
print(c)
|
#Ageel 9/1/2019
#100 Days of Python
#Day 14 - List2
moviesToWatch = ["John Wick 3","Pets 2","Shaw and Hobbs","Crawl"]
print("My movies to watch "+str(moviesToWatch[0:3]))
print ("Is the Lion King in the list ? " + str("Lion King" in moviesToWatch))
print (str(" Beetlejuice"*3))
infinityStones1 = ["The Space Stone... |
#!/usr/bin/python\
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
# init list with pin numbers\
pinList = [2, 3, 14, 17]
# loop through pins and set mode and state to 'low'\
for i in pinList:
GPIO.setup(i, GPIO.OUT)
GPIO.output(i, GPIO.HIGH)
# main loop\
try:
GPIO.output(2, GPIO.LO... |
#
# Tests for NSArchiver/NSKeyedArchiver interop with pure ObjC code.
# That is, when a Python script uses an archiver to write out
# a data structure with basic python types (list, tuple, unicode,
# str, int, float) a pure ObjC program should be able to read
# that archive as a datastructure with the corresponding Coc... |
from setuptools import setup
setup(
name='pybem',
version='0.1.2',
author="Klim Naydenov",
author_email="knaydenov@gmail.com",
description='This package provides helpers for BEM classes generation',
url='https://github.com/knaydenov/pybem',
install_requires=[],
packages=['pybem'],
... |
import sys
import os
import nibabel as nib
import numpy as np
import bigbadbrain as bbb
import warnings
warnings.filterwarnings("ignore")
sys.path.insert(0, '/home/users/brezovec/.local/lib/python3.6/site-packages/lib/python/')
import ants
def main(args):
directory = args[0]
motcorr_directory = args[1]
ma... |
#!/usr/bin/python
def smallestEvenlyDivisible( divisors ):
product = 1
currentNum = 2
numsToFactor = divisors
while numsToFactor:
anyDivisible = False
updatedNumsToFactor = []
for numToFactor in numsToFactor:
if numToFactor % currentNum == 0:
anyDivis... |
# Crie uma classe que modele uma pessoa
# a)Atributos nome, idade, peso e altura
# b)Métodos envelhecer, engordar, emagrecer, crescer
# Por padrão, a cada ano que a pessoa envelhece, sendo a idade dela menor que 21 anos, ela deve crescer 0,5 cm
class Pessoa:
def __init__(self, nome, idade, peso, altura):
se... |
from itertools import product
def first():
lines = open("14/dd.txt", "r").read().splitlines()
segments = []
temp = []
for line in lines:
if "mask" in line:
if temp:
segments.append(temp.copy())
temp = [line]
else:
temp.append(line)
... |
import os
from config_generation_utils import dump_json_file, fetch_from_env
TARGET_FILE_PATH = os.path.join("./user_identity_service/db_content.json")
TO_FETCH_FROM_ENV = [
('ROOT_USER_NAME', 'ROOT_PASSWORD'),
]
def create_db_content() -> None:
env_content = fetch_from_env(to_fetch=TO_FETCH_FROM_ENV)
... |
# Generated by Django 3.2.4 on 2021-07-13 08:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('data_aggregator', '0012_alter_jobtype_type'),
]
operations = [
migrations.RenameField(
model_name='participation',
o... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp2d
from scipy.optimize import minimize
df = pd.read_csv("measure.csv")
dv = df.values
norm = np.linalg.norm(dv[:, :2], axis=1)
mask = norm < 20
print(mask[:10])
d = dv[mask]
print(d.shape, norm[mask].shape)
x_i... |
"""
Scrape projections from Hashtag Basketball
"""
import datefinder
import lxml.html
import pandas
import requests
from datetime import datetime
def main():
projections_page = download_projections_page()
root = lxml.html.fromstring(projections_page) # parse HTML
projections = extract_projections(r... |
import CryptoCompareWebSocketOHLCV as cws
import unittest
from io import StringIO
from unittest import mock
import datetime
import pytz
# TODO:
# Add testing for socketio client + start()
# Maybe add tests for backup_logs() + get_date_filename
# Integration tests for DB ???
# Create 'real' Factory for Trade... |
import pygame as pg
import sys
from settings import *
from sprites import *
from os import path
import numpy as np
import math
vec = pg.math.Vector2
class Game:
def __init__(self):
pg.init()
self.screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption(TITLE)
... |
import unittest
import day_7
challenge = (
"llyhqfe (21)",
"vpbdpfm (74) -> ndegtj, wnwxs",
"dosteiu (262) -> vliyv, rfxmk, nulxd, tckql",
"leqnli (222) -> wuttw, nckca",
"cgztcyz (59) -> zbtmpkc, lleaucw, zxvjkqv, tqjyoj",
"dqfti (67)",
"vsjhe (34) -> zpbbgqh, menyi, ksasli, uahdbi, ccfiz... |
from collections import Counter
from project.models.song_info import song
from project.models.inverted_index import InvertedIndex, convert_list
from project.models.base import Database
import math
num_of_song = 99
name_weight = 2
def get_weight_list(text):
str_list = convert_list(text)
res = Counter()
fo... |
from pymoo.model.crossover import Crossover
from pymoo.operators.crossover.util import crossover_mask
import numpy as np
from random import random,randrange
def computeConsensus(solution,seqs,l_mer):
consensus = ""
j = -1
for i in range(l_mer):
j += 1
a = c = g = t = 0
for k in ran... |
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
res = {}
for str in strs:
res.setdefault(''.join(sorted(str)), []).append(str)
return list(res.values())
solution = Solution()
# ans = solution.groupAnagrams(["eat", "tea", "... |
from mongo import db
def get_user(uid, allow_test=False):
query = {'_id' : uid}
if not allow_test:
query['is_test'] = False
return db.users.find_one(query)
def get_all_users(limit=0, allow_test=False):
query = {}
if not allow_test:
query['is_test'] = False
return list({"name":i... |
# -*- coding: utf-8 -*-
def strToNumBase(numStr,base):
if numStr=='1':
return 1
elif base==10:
return int(numStr)
else:
power=len(numStr)-1
num=0
for digit in numStr:
if digit=='1':
num+=base**power
power-=1
... |
import random
from pygame.sprite import Group
from plane.base_plane import BasePlane
from plane.missile_gun import MissileGun
class EnemyPlane(BasePlane):
def __init__(self, ai_settings, screen):
BasePlane.__init__(self, ai_settings, screen, "images/ship6small.png")
self.min = random.randint(0, ... |
# PEP8
# Комментарий комметариевич
# name = input('Ваше имя?\n')
while True:
age = input('Возвраст, число \n')
if age.isdigit():
age = int(age)
break
else:
print('Введите чЕсло')
print(age)
# this_year = 2020
#
# if age.isdigit():
# age = int(age)
# b_year = this_year - age
... |
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel
# Define choices
from enum import Enum
class Species(str, Enum):
human = 'human'
alien = 'alien'
class User(BaseModel):
id: int
name: str
# Optional: it's either the specified type or `None` by def... |
import urllib
import bson
from datetime import datetime
import setting
# use constant
timestamp = datetime.utcnow().strftime("%Y_%m_%d_%H_%M_%S")
db = setting.db_connection["PW_" + timestamp]
#This method is used to get entries for both APIs and Mashups from Programmableweb
def getEntries(service_type):
#the page ... |
import numpy as np
from caffe2.python import \
core, device_checker, gradient_checker, test_util, workspace
from caffe2.proto import caffe2_pb2, caffe2_legacy_pb2
import collections
import sys
import unittest
core.GlobalInit(["python"])
if workspace.has_gpu_support and workspace.NumberOfGPUs() > 0:
gpu_devic... |
import shelve
from typing import Any, Dict
from uuid import UUID, uuid4
class Database:
def __init__(self, filename="shelve.db"):
self.filename = filename
def create(self, item: Any) -> UUID:
with shelve.open(self.filename) as db:
uuid = uuid4()
db[uuid] = item
... |
# Car button codes
class CruiseButtons:
# VAL_ 69 SpdCtrlLvr_Stat 32 "DN_1ST" 16 "UP_1ST" 8 "DN_2ND" 4 "UP_2ND" 2 "RWD" 1 "FWD" 0 "IDLE" ;
RES_ACCEL = 16
DECEL_SET = 32
CANCEL = 1
MAIN = 2
#car chimes: enumeration from dbc file. Chimes are for alerts and warnings
class CM:
MUTE = 0
SINGL... |
import os
import js2py
import sqlite3
from django.template.loader import render_to_string
import cv2
from django.contrib.auth.models import User
import numpy as np
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from dj... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'kieran-nichols'
SITENAME = 'Kieran Nichols'
SITEURL = 'https://www.kieran-nichols.com'
PATH = 'content'
OUTPUT_PATH = 'docs/'
TIMEZONE = 'US/Central'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when ... |
"""TcEx Framework Module"""
# standard library
import logging
from abc import ABC
from collections.abc import Generator
from typing import Any
# third-party
from requests import Response, Session
from requests.exceptions import ProxyError, RetryError
# first-party
from tcex.api.tc.v3.tql.tql import Tql
from tcex.exit... |
#Tim Grose - timothy.h.grose@gmail.com
#instructions for running locally:
#download as a .py. save as main.py into lq_app folder.
#open command prompt in folder containing lq_app folder and type "bokeh serve lq_app --show"
#for instructions on how to employ on heroku, see readme file
#coding: utf-8
#import packages
... |
#!/usr/bin/python3
def knapsack(W, wt, val):
k = [[0 for _ in range(W+1)] for _ in range(len(wt) + 1)]
for i in range(1, len(wt)+1):
for w in range(1, W+1):
if wt[i-1] <= w:
k[i][w] = max(val[i-1] + k[i-1][w-wt[i-1]], k[i-1][w])
else:
k[i][w] = k... |
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7,GPIO.OUT)
for x in range(0,1):
GPIO.output(7,True)
time.sleep(.8)
GPIO.output(7,False)
time.sleep(.8)
GPIO.cleanup() |
import GPy
from GPyOpt.methods import BayesianOptimization
def optimizer_func(X, Y, BatchSize):
'''
Bayesian Optimizer Function
BatchSize is the number of suggestions for the next rounds
X should be the input variables
Y should be the metric to be optimized
'''
bds = [{'name': 'x1', ... |
import mysql
from configparser import ConfigParser
from mysql.connector import (connection)
from mysql.connector import errorcode
class Conexion:
def __init__(self):
self.Conexion = None
def crear_conexion(self):
config_object = ConfigParser()
config_object.read("config/config.ini")
... |
string_in1=input("input costs")
string_in2=input("input costs")
records = []
records.append(string_in1)#
records.append(string_in2)#
print(records)
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 7 12:58:07 2017
@author: wangxj
"""
#!/usr/bin/python
#coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
# 获取所有的自带样式
print (plt.style.available)
# 使用自带的样式进行美化
plt.style.use("ggplot")
fig, axes = plt.subplots(ncols = 2, nrows = 2)
# 四个子图的坐标轴赋予四个对象
ax1... |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: jescudero
#
# Created: 28/04/2015
# Copyright: (c) jescudero 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
imp... |
import numpy as np
import matplotlib.pyplot as plt
M1=np.array([1,1])#vektor srednjih vrednosti
M2=np.array([5,2])#vektror srednjih vrrednosti
Sigma1=np.array([[2,1],[1,1]])#kovariaciona matrica, prve klase
Sigma2=np.array([[3,-1],[-1,2]])#kovariaciona matrica druge klase
np.random.seed(0)
N=700
P1=P2=0.5
y1, y2=np.ra... |
__title__ = "django_invoice"
__summary__ = "Django + Stripe Made Easy"
__uri__ = "https://github.com/josephmisiti/django_invoice/"
__version__ = "0.7.0"
__author__ = "Daniel Greenfeld"
__email__ = "josephmisiti@gmail.com"
__license__ = "BSD"
__license__ = "License :: OSI Approved :: BSD License"
__copyright__ = "Cop... |
# Copyright 2021 The Layout Parser team and Paddle Detection model
# contributors. 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... |
def greatest_number(lst) :
size = len(lst)
myHigh = lst[0]
for item in lst :
if myHigh < item :
myHigh = item
else :
continue
return myHigh
myList = list()
for i in range(4) :
myList.append(int(input("enter the number")))
a = greatest_number(myList)
print "gr... |
def letter_combination(digits: str):
letter_mapping = {
2: list('abc'),
3: list('def'),
4: list('ghi'),
5: list('jkl'),
6: list('mno'),
7: list('pqs'),
8: list('tuv'),
9: list('wxyz')
}
def _gen_comb(cur_comb, cur_idx):
if cur_idx == l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.